#! /bin/bash

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

rebuild () {
    tar xzf silo-git20110806.tar.gz
    cd silo-dfe79d6
    bunzip2 -c ../silo-1.4.14-dietpc-patch.bz2 | patch -p1 -b
    make
    # FIXME: It's possible to compile silo/silo 64-bit, but need to disable
    # typedefs of __u64 and __64 in /usr/include/ext2fs/ext2_types.h, and
    # override CC set in Rules.make.
    strip -R .note -R .comment silo/silo
    mkdir -p ../silo/sbin ../silo-runtime/boot/silo
    cp first/{fd.b,first.b,ultra.b} ../silo-runtime/boot/silo/
    cp first-isofs/isofs.b ../silo-runtime/boot/silo/
    cp second/second.b ../silo-runtime/boot/silo/
    cp silo/silo ../silo/sbin/
    cd ..
    rm -rf silo-dfe79d6
}

ARCH=`ipkg -V 0 print_architecture | tail -n 1 | cut -f2 -d' '`
[ "$ARCH" != 'sparc' ] && exit 0

while read FN; do
    eval "[ -e $FN ] || rebuild"
done < MANIFEST

for CTRLFILE in */CONTROL/control; do
    sed -i -e "s/__ARCH__/$ARCH/g" $CTRLFILE
    sudo ipkg-build -o root -g root `dirname $CTRLFILE`/..
done
