#! /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 util-linux-2.12r.tar.bz2
    cd util-linux-2.12r
    ed -s MCONFIG >/dev/null <<EOF
1,\$s/\\\$(CPUOPT) //
1,\$s/-O2 /$CFLAGS /
w
q
EOF
    ed -s configure >/dev/null <<EOF
/^CFLAGS=/d
w
q
EOF
    ./configure
    ed -s make_include >/dev/null <<EOF
/^HAVE_BLKID=/d
i
HAVE_BLKID=no
.
w
q
EOF
    ed -s disk-utils/mkfs.c >/dev/null <<EOF
/"PATH=\/sbin:/
s@/sbin:@/sbin:/usr/sbin:/usr/local/sbin:@
w
q
EOF
    make -C lib
    make -C disk-utils mkfs
    make -C disk-utils mkfs.cramfs
    make -C misc-utils mcookie
    make -C mount mount
    strip -R .note -R .comment disk-utils/mkfs disk-utils/mkfs.cramfs \
	    misc-utils/mcookie mount/mount
    mkdir -p ../mkfs/sbin ../mcookie/bin ../mount/bin
    sudo cp disk-utils/mkfs.cramfs /usr/local/bin/
    cp disk-utils/mkfs ../mkfs/sbin/
    cp misc-utils/mcookie ../mcookie/bin/
    cp mount/mount ../mount/bin/
    cd ..
    rm -rf util-linux-2.12r
}

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
