#! /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 rfb-0.6.1.1.tar.gz
    cd rfb-0.6.1.1
    bunzip2 -c ../rfb-0.6.1.1-dietpc-patch.bz2 | patch -p1 -b
    for MF in lib/Makefile x0rfbserver/Makefile; do
	ed -s $MF >/dev/null <<EOF
1,\$s/-O3/$CXXFLAGS -fsigned-char/
w
q
EOF
done
    make -C lib
    cd x0rfbserver
    ed -s x0rfbserver.cc >/dev/null <<EOF
/size_t laddr = sizeof/
s/size_t/socklen_t/
w
q
EOF
    make
    gcc -o x0rfbserver *.o ../lib/librfb.a -lz -lm -L/usr/local/lib -lXext \
	-lX11 -lXpm -Wl,-Bstatic -lxclass -lXtst -lstdc++ -Wl,-Bdynamic -lwrap
    strip -R .note -R .comment x0rfbserver
    cp x0rfbserver ../../x0rfbserver/bin/
    cd ../..
    rm -rf rfb-0.6.1.1
}

(cd xclass; ./build.sh)

chmod 600 x0rfbserver/etc/.x0rfbserver

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
