#! /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 () {
    # First, the vol_id build (udev 141 was the last to include vol_id):
    tar xjf udev-141.tar.bz2
    cd udev-141
    bunzip2 -c ../udev-128-e2compr-patch.bz2 | patch -p1 -b
    ./configure --prefix=/usr --exec-prefix= --sysconfdir=/etc --disable-shared
    make -C extras/volume_id
    strip -R .note -R .comment extras/volume_id/vol_id
    mkdir -p ../vol-id/sbin
    cp extras/volume_id/vol_id ../vol-id/sbin/
    cd ..
    rm -rf udev-141

    # Then the libudev build, using a newer version (builds later than 175
    # include a libblkid dependency higher than Squeeze can satisfy):
    tar xjf udev-175.tar.bz2
    cd udev-175
    bunzip2 -c ../udev-175-missing-triggerhappy.patch.bz2 | patch -p1 -b
    # Lenny needs this:
    #bunzip2 -c ../udev-175-simple-cloexec.patch.bz2 | patch -p1 -b
    ./configure --prefix= --with-pic --without-selinux \
	    --with-pci-ids-path=/usr/share/misc/pci.ids \
	    --with-usb-ids-path=/usr/share/misc/usb.ids --enable-static \
	    --disable-gudev --disable-introspection --enable-floppy \
	    --with-firmware-path=/lib/firmware
    make libudev/libudev.la
    strip -R .note -R .comment libudev/.libs/libudev.so.0
    mkdir -p ../libudev0/lib
    cp libudev/.libs/libudev.so.0 ../libudev0/lib/
    cd ..
    rm -rf udev-175
}

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
