#! /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 () {
    if [ -e /usr/local/lib/libcrypto.a ]; then
	SSLROOT='/usr/local'
    else
	echo 'WARNING: Custom OpenSSL library not present' 1>&2
	echo 'WARNING: May result in large binary!' 1>&2
	SSLROOT='/usr'
    fi

    tar xzf rdesktop-1.7.1.tar.gz
    cd rdesktop-1.7.1
    bunzip2 -c ../rdesktop-1.5.0-dietpc-patch.bz2 | patch -p1 -b
    ./configure --prefix=/usr --with-openssl=$SSLROOT --with-sound=oss \
	    --enable-static-openssl
    sed -i -e 's/-DHAVE_ICONV=1\>//' Makefile
    make
    strip -R .note -R .comment rdesktop
    mkdir -p ../rdesktop/share/rdesktop/keymaps \
	    ../rdesktop-keymaps/share/rdesktop/keymaps
    cp rdesktop ../rdesktop/bin/
    cp keymaps/* ../rdesktop-keymaps/share/rdesktop/keymaps/
    mv ../rdesktop-keymaps/share/rdesktop/keymaps/{common,modifiers,en-us} \
	    ../rdesktop/share/rdesktop/keymaps/
    rm ../rdesktop-keymaps/share/rdesktop/keymaps/convert-map
    cd ..
    rm -rf rdesktop-1.7.1
}

[ -x ../openssl/build.sh ] && (cd ../openssl; ./build.sh)

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
