#! /bin/bash

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

# Must first compile and install later version of sed (than comes with woody),
# or this won't work.

rebuild () {
    tar xjf busybox-1.20.2.tar.bz2
    cd busybox-1.20.2
    bunzip2 -c ../busybox-1.20.0-dietpc-patch.bz2 | patch -p1 -b
    bunzip2 -c ../busybox-1.20.2-woody.patch.bz2 | patch -p1 -b
    cp ../dietpc_bbconfig-1.20.2 .config
    ed -s .config >/dev/null <<EOF
/^CONFIG_EXTRA_CFLAGS=/d
i
CONFIG_EXTRA_CFLAGS="$CFLAGS"
.
w
q
EOF
    case "`uname -m`" in
    x86_64)
	ed -s .config >/dev/null <<EOF
/^# CONFIG_SETARCH /d
i
CONFIG_SETARCH=y
.
w
q
EOF
	;;
    sparc*)
	ed -s .config >/dev/null <<EOF
/^# CONFIG_FEATURE_SUN_LABEL /d
i
CONFIG_FEATURE_SUN_LABEL=y
.
w
q
EOF
	;;
    esac
    make oldconfig >/dev/null CC=gcc-3.0
    make CC=gcc-3.0
    cp busybox ../busybox/bin/
    chmod u+s ../busybox/bin/busybox
    cd ..
    rm -rf busybox-1.20.2
}

chmod 0600 busybox/etc/busybox.conf
mkdir -p busybox/bin
ln -sf busybox busybox/bin/sh
ln -sf ../bin/busybox busybox/sbin/modprobe
[ -c busybox/dev/console ] || sudo mknod busybox/dev/console c 5 1
[ -c busybox/dev/null ] || sudo mknod busybox/dev/null c 1 3
sudo chown -R `id -nu`:`id -ng` busybox/dev

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
