#! /bin/bash

trap "echo '*** BUILD FAILED! ***' 1>&2" ERR
set -ex -o pipefail
umask 022
export PATH='/bin:/usr/bin:/usr/local/bin'
export CFLAGS=${CFLAGS:--Os}
export CXXFLAGS=${CXXFLAGS:--Os}

rebuild () {
    tar xzf xrdp-0.4.2.tar.gz
    cd xrdp-0.4.2
    bunzip2 -c ../xrdp-0.4.2-dietpc.patch.bz2 | patch -p1 -b
    make
    make -C sesman no-pam
    strip -R .note -R .comment vnc/libvnc.so xrdp/xrdp sesman/sesman \
	    sesman/sessvc
    mkdir -p ../xrdp/bin ../xrdp/lib/xrdp ../xrdp/share/xrdp
    cp xrdp/rsakeys.ini ../xrdp/etc/xrdp/
    cp xrdp/xrdp sesman/sesman ../xrdp/bin/
    cp vnc/libvnc.so sesman/sessvc ../xrdp/lib/xrdp/
    cp xrdp/{ad256.bmp,cursor0.cur,cursor1.cur,Tahoma-10.fv1,xrdp256.bmp} \
	    ../xrdp/share/xrdp/
    cd ..
    rm -rf xrdp-0.4.2
}

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
