#! /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 hfsplus_1.0.4.src.tar.bz2
    cd hfsplus-1.0.4
    ln -s /usr/bin/libtool
    ln -s /usr/share/libtool/ltmain.sh
    make -f Makefile.cvs
    CC=gcc-3.4 ./configure --prefix=/usr --sysconfdir=/etc --disable-shared
    ed -s libhfsp/src/unicode.c >/dev/null <<EOF
/<linux\/string.h\>/
s@linux/@@
.
w
q
EOF
    ed -s src/glob.c >/dev/null <<EOF
/case NULL:/
s/NULL/'\\\0'/
w
q
EOF
    ed -s src/hpmkdir.c >/dev/null <<EOF
/include <errno.h>/d
a
# include <errno.h>
.
w
q
EOF
    make -C libhfsp/src CFLAGS="$CFLAGS"
    make -C src CFLAGS="$CFLAGS"
    cd src
    strip -R .note -R .comment hpcd hpcopy hpfsck hpls hpmkdir hpmount hppwd \
	    hprm hpumount
    mkdir -p ../hfsplus/bin
    cp hpfsck ../hfsplus/sbin/
    cp hpcd hpcopy hpls hpmkdir hpmount hppwd hprm hpumount ../hfsplus/bin/
    cd ../..
    rm -rf hfsplus-1.0.4
}

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

mkdir -p hfsplus/sbin
ln -sf hpfsck hfsplus/sbin/fsck.hfsplus

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
