#! /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 dump-0.4b44.tar.gz
    cd dump-0.4b44
    ./configure --prefix='' --enable-rmt --disable-readline \
	    --disable-transselinux
    make -C compat/lib
    make -C rmt GLIBS='-L../compat/lib -lcompat'
    # FIXME: need to make some decisions about dynamic vs static, whether to
    # include readline and selinux
#     gcc  -o dump *.o ../common/dumprmt.o -L../compat/lib -lcompat \
#	    /usr/lib/libext2fs.a -lz /usr/lib/libblkid.a  /usr/lib/libbz2.a \
#	    /usr/lib/libcom_err.a  -lrt -l uuid
#    gcc  -o restore *.o ../common/dumprmt.o -L../compat/lib -lcompat \
#	    /usr/lib/libext2fs.a -lz /usr/lib/libbz2.a /usr/lib/libe2p.a
    strip -R .note -R .comment rmt/rmt
    mkdir -p ../rmt/sbin
    cp rmt/rmt ../rmt/sbin/
    cd ..
    rm -rf dump-0.4b44
}

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
