#! /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 zisofs-tools-1.0.8.tar.bz2
    #cd zisofs-tools-1.0.8
    #./configure --prefix=/usr
    #make
    #strip -R .note -R .comment mkzftree
    #mkdir -p ../cdrtools-minimal/bin/
    #cp mkzftree ../cdrtools-minimal/bin/
    #cd ..
    tar xjf cdrtools-3.00.tar.bz2
    cd cdrtools-3.00
    chmod u+w DEFAULTS/Defaults.linux
    ed -s DEFAULTS/Defaults.linux >/dev/null <<EOF
/^DEFCCOM=/
s/=.*\$/=gcc/
/^LDPATH=/
s/=.*\$/=/
/^RUNPATH=/
s/=.*\$/=/
/^INS_BASE=/
s@=.*\$@=/usr@
w
q
EOF
    case "`uname -m`" in
    arm*)
	ln -s armv4l-linux-gcc.rul  RULES/`uname -m`-linux-gcc.rul 2>/dev/null
    ;;
    esac
    make COPTOPT="$CFLAGS" LIB_ACL_TEST='/usr/lib/libacl.a'
    strip -R .note -R .comment rscsi/OBJ/*/rscsi cdrecord/OBJ/*/cdrecord \
	    mkisofs/OBJ/*/mkisofs
    mkdir -p ../cdrtools-minimal/bin ../rscsi/sbin
    cp rscsi/OBJ/*/rscsi ../rscsi/sbin/
    chmod 4755 ../rscsi/sbin/rscsi
    cp cdrecord/OBJ/*/cdrecord mkisofs/OBJ/*/mkisofs ../cdrtools-minimal/bin/
    cd ..
    rm -rf cdrtools-3.00
}

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
