#! /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 tcp_wrappers_7.6-ipv6.4.tar.gz
    cd tcp_wrappers_7.6-ipv6.4
    bunzip2 -c ../tcp_wrappers_7.6-ipv6.4-dietpc-patch.bz2 | patch -p1 -b
    chmod u+w Makefile
    ed -s Makefile >/dev/null <<EOF
/^CFLAGS\W=/
s/-Os/$CFLAGS/
w
q
EOF
    make linux
    gcc -shared -o libwrap.so.0 -Wl,-soname=libwrap.so.0 `ar t libwrap.a`
    strip -R .note -R .comment libwrap.so.0
    cp libwrap.so.0 ../libwrap0/lib/
    cd ..
    rm -rf tcp_wrappers_7.6-ipv6.4
}

mkdir -p libwrap0/lib
ln -sf libwrap.so.0 libwrap0/lib/libwrap.so

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
