#! /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 sysvinit-2.88dsf.tar.bz2
    cd sysvinit-2.88dsf
    bunzip2 -c ../sysvinit-2.88dsf-dietpc-patch.bz2 | patch -p1 -b
    cd src
    ed -s init.h >/dev/null <<EOF
/^#define PATH_DEFAULT/d
i
#define PATH_DEFAULT   "PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin"
.
w
q
EOF
    ed -s Makefile >/dev/null <<EOF
/^CFLAGS\W/
s/-O2/$CFLAGS/
w
q
EOF
    make halt
    make init
    strip -R .note -R .comment init halt
    cp init halt ../../sysvinit/sbin/
    chmod u+s ../../sysvinit/sbin/init
    cd ../..
    rm -rf sysvinit-2.88dsf
}

ln -sf sbin/init sysvinit/init
ln -sf halt sysvinit/sbin/reboot

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
