#! /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 xjf spice-protocol-0.8.2.tar.bz2
    cd spice-protocol-0.8.2
    ./configure --prefix=/usr/local --datarootdir=/usr/local/lib
    sudo make install
    cd ..
    rm -rf spice-protocol-0.8.2

    # N.B. Must use host OpenSSL, not /usr/local version.
    tar xjf spice-0.8.2.tar.bz2
    cd spice-0.8.2
    bunzip2 -c ../spice-0.8.1-mwmhint-patch.bz2 | patch -p1 -b
    # One of the bigend fixes has been applied in 0.10.1.
    bunzip2 -c ../spice-0.8.2-bigendfix-patch.bz2 | patch -p1 -b
    # Must do something to disable Werror in 0.10.1!
    ./configure --prefix=/usr/local --sysconfdir=/etc --localstatedir=/var \
	    --with-pic --without-sasl
    make -C client
    cd client
    # 0.10.1 needs Xinerama as well.
    gcc -o spicec *.o x11/*.o ../common/.libs/libspice-common.a -Wl,-Bstatic \
	    -lssl -lcrypto -lstdc++ -Wl,-Bdynamic -ljpeg -lm -ldl -lpthread \
	    -lrt -lz -lasound -lX11 -lXext -lXrandr -lXfixes \
	    /usr/local/lib/libpixman-1.so /usr/local/lib/libcelt051.so
    strip -R .note -R .comment spicec
    [ -n "`which upx`" ] && upx -9 spicec
    mkdir -p ../../spicec/bin
    cp client/x11/spicec ../../spicec/bin/

    # Server: i386 and amd64 only.
    # Need ~/openssl-0.9.8r/crypto/bn/bn_prime.o and
    # ~/openssl-0.9.8r/crypto/rsa/rsa_gen.o to dodge the OpenSSL dependency.
    # Can't just steal them from /usr/lib/libcrypto.a, need -fPIC compilation.
    # Patch in to am_libspice_server_la_OBJECTS in server/Makefile.
    #cd ..
    #rm -rf spice-0.8.2
}

if [ ! -e /usr/local/lib/libcelt051.so.0 ]; then
    if [ -d ../celt ]; then
	(cd ../celt; ./build.sh)
    else
	echo "Missing libcelt 0.5.1 library.  This ain't gonna work." 1>&2
	exit 1
    fi
fi

if [ -z "`which upx`" ]; then
    if [ -d ../upx ]; then
	(cd ../upx; ./build.sh)
    else
	echo "UPX not present, will not be able to compress spicec binary." 1>&2
    fi
fi

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
