#! /bin/bash

trap "echo '*** BUILD FAILED! ***' 1>&2" ERR
set -ex -o pipefail
umask 022
export PATH='/bin:/usr/bin:/usr/local/bin:~/diet-pc/tools'
export CFLAGS=${CFLAGS:--Os}
export CXXFLAGS=${CXXFLAGS:--Os}

rebuild () {
    tar xjf libdrm-2.4.35.tar.bz2
    cd libdrm-2.4.35
    bunzip2 -c ../libdrm-2.4.35-lenny-open_memstream-fix.patch.bz2 | patch \
	    -p1 -b
    bunzip2 -c ../libdrm-2.4.35-stop-intel-veto.patch.bz2 | patch -p1 -b
    ./configure --prefix=/usr/local --disable-libkms
    # FIXME: arm/armel can't build libdrm-intel
    # Possible with help of libatomic-ops-dev, need to hack configure script
    # to prevent veto of --enable-intel and (on Squeeze but not Wheezy?)
    # perform a manual link.
    make
    sudo make install # Squeeze only
    strip -R .note -R .comment .libs/libdrm.so.2 \
	    nouveau/.libs/libdrm_nouveau.so.2 radeon/.libs/libdrm_radeon.so.1 \
	    intel/.libs/libdrm_intel.so.1
    mkdir -p ../libdrm2/lib ../libdrm-nouveau2/lib ../libdrm-radeon1/lib \
	    ../libdrm-intel1/lib
    cp .libs/libdrm.so.2 ../libdrm2/lib/
    cp nouveau/.libs/libdrm_nouveau.so.2 ../libdrm-nouveau2/lib/
    cp radeon/.libs/libdrm_radeon.so.1 ../libdrm-radeon1/lib/
    cp intel/.libs/libdrm_intel.so.1 ../libdrm-intel1/lib/
    cd ..
    rm -rf libdrm-2.4.35
}

while read FN; do
    eval "[ -e $FN ] || rebuild"
done < MANIFEST

ARCH=`ipkg -V 0 print_architecture | tail -n 1 | cut -f2 -d' '`
for CTRLFILE in */CONTROL/control; do
    sed -i -e "s/__ARCH__/$ARCH/g" $CTRLFILE
    sudo ipkg-build -o root -g root `dirname $CTRLFILE`/..
done
