#! /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 e3-2.7.1.tar.gz
    cd e3-2.7.1
    bunzip2 -c ../e3-2.7.1-dietpc.patch.bz2 | patch -p1 -b
    case "`uname -m`" in
    *86)
	make
	;;
    arm*)
	make -C armlinux AS=as LD=ld STRIP=strip
	ln -s armlinux/e3arm e3
	;;
    *)
	make -C e3c PREFIX=/usr CFLAGS="$CFLAGS"
	strip -R .note -R .comment e3c/e3c
 	ln -s e3c/e3c e3
	;;
    esac
    cp e3 ../e3/bin/
    cd ..
    rm -rf e3-2.7.1
}

mkdir -p e3/bin
ln -sf e3 e3/bin/e3ws
case "`uname -m`" in
*86|arm*)
    ln -sf e3 e3/bin/e3em
    ln -sf e3 e3/bin/e3ne
    ln -sf e3 e3/bin/e3pi
    ln -sf e3 e3/bin/e3vi
    ;;
esac

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
