#! /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 xzf glib-1.2.10.tar.gz
    cd glib-1.2.10
    bunzip2 -c ../glib-1.2.10-gcc4-patch.bz2 | patch -p1 -b
    # config.sub is too old for amd64 et al, can't run autoreconf due to age
    # of configure.in, so selectively update automake files.
    AMVERS=`automake --version | awk '{print $NF; exit}' | cut -f1-2 -d.`
    for FILE in config.guess config.sub install-sh missing; do
	cp /usr/share/automake-$AMVERS/$FILE .
    done
    cp /usr/share/libtool/config/ltmain.sh .
    ./configure --prefix=/usr/local --sysconfdir=/etc --localstatedir=/var
    # Glib 1.2 no longer exists in Squeeze, so install to /usr/local.
    cp /usr/bin/libtool .
    sudo make install
    strip -R .note -R .comment .libs/libglib-1.2.so.0 \
	    gmodule/.libs/libgmodule-1.2.so.0 gthread/.libs/libgthread-1.2.so.0
    mkdir -p ../libglib12-0/lib
    cp .libs/libglib-1.2.so.0 gmodule/.libs/libgmodule-1.2.so.0 \
	    gthread/.libs/libgthread-1.2.so.0 ../libglib12-0/lib/
    cd ..
    rm -rf glib-1.2.10
}

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
