#! /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 dosfstools-3.0.16.tar.gz
    cd dosfstools-3.0.16
    ed -s Makefile >/dev/null <<EOF
/^OPTFLAGS =/
s/-O2/$CFLAGS/
/^DEBUGFLAGS =/
s/^/#/
w
q
EOF
    make
    strip -R .note -R .comment dosfsck mkdosfs
    cp dosfsck ../dosfsck/sbin/
    cp mkdosfs ../mkdosfs/sbin/
    cd ..
    rm -rf dosfstools-3.0.16
}

mkdir -p dosfsck/sbin mkdosfs/sbin
ln -sf dosfsck dosfsck/sbin/fsck.msdos
ln -sf dosfsck dosfsck/sbin/fsck.vfat
ln -sf mkdosfs mkdosfs/sbin/mkfs.msdos
ln -sf mkdosfs mkdosfs/sbin/mkfs.vfat

while read FN; do
    [ -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
