#! /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 rxvt-2.7.10.tar.gz
    cd rxvt-2.7.10
    bunzip2 -c ../rxvt-2.7.10-norgbdb.patch.bz2 | patch -p1 -b
    CFLAGS="$CFLAGS -fsigned-char" ./configure --prefix=/usr \
	    --enable-xterm-scroll --enable-xgetdefault --enable-mousewheel \
	    --enable-smart-resize --enable-24bit --disable-backspace-key \
	    --disable-delete-key --enable-languages
    ed -s src/feature.h >/dev/null <<EOF
/^# define X11USRLIBDIR/
s@X11R6/@@
w
q
EOF
    make CFLAGS="$CFLAGS -fsigned-char"
    strip -R .note -R .comment src/rxvt
    mkdir -p ../rxvt/bin
    cp src/rxvt ../rxvt/bin/
    cd ..
    rm -rf rxvt-2.7.10
}

ln -sf rxvt rxvt/bin/xterm

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
