#! /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 hfsutils-3.2.6.tar.gz
    cd hfsutils-3.2.6
    ./configure --prefix=/usr --sysconfdir=/etc
    make
    make -C hfsck
    strip -R .note -R .comment hfsutil hfsck/hfsck
    cp hfsck ../hfsutils/sbin/
    cp hfsutil ../hfsutils/bin/
    cd ..
    rm -rf hfsutils-3.2.6
}

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

mkdir -p hfsutils/sbin hfsutils/bin
ln -sf hfsck hfsutils/sbin/fsck.hfs
for link in hattrib hcd hcopy hdel hdir hformat hls hmkdir hmount hpwd \
	hrename hrmdir humount hvol; do
    ln -sf hfsutil hfsutils/bin/$link
done

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
