#! /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 xf4vnc-20071208.tar.bz2
    cd xf4vnc/xc/config/cf
    ed -s host.def >/dev/null <<EOF
/GccWarningOptions/
s@^/\* @@
/ \*\/\$/
s@ \*/\$@@
\$a
#define BuildGlxExt NO
#define BuildXKB YES
#define BuildIPv6 NO
#define BuildFreeType NO
#define UseFreetype2 NO
#define XF86Server NO
#define OptimizedCDebugFlags $CFLAGS
.
w
q
EOF
    ed -s site.def >/dev/null <<EOF
/^#define ProjectRoot/d
i
#define ProjectRoot /usr
.
w
q
EOF
    ed -s linux.cf >/dev/null <<EOF
/|| defined(MipsArchitecture) /
s/|| defined(MipsArchitecture) //
w
q
EOF
    touch version.def date.def
    cd ../../../libvncauth
    xmkmf ../xc
    make
    cd ../xc
    make World
    rm -f programs/Xserver/Xvnc
    make -C programs/Xserver FREETYPE2LIB="-Wl,-Bstatic -lfreetype \
	    -Wl,-Bdynamic"
    strip -R .note -R .comment programs/Xserver/Xvnc
    mkdir -p ../../xvnc/bin
    cp programs/Xserver/Xvnc ../../xvnc/bin/
    cd ../..
    rm -rf xf4vnc
}

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
