#! /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 xjf transmission-1.76.tar.bz2
    cd transmission-1.76
    ed -s configure >/dev/null <<EOF
/if test "x\$GCC"/
.,.+3s/^/#/
w
q
EOF
    CFLAGS="$CFLAGS -fPIC" CXXFLAGS="$CFLAGS -fPIC" ./configure --prefix=/usr \
	    --sysconfdir=/etc --disable-gtk --enable-cli --disable-libnotify \
	    --enable-daemon --enable-shared
    make
    cd libtransmission
    gcc -shared -Wl,-soname -Wl,libtransmission.so.1 -o libtransmission.so.1 \
	    `ar t libtransmission.a` ../third-party/libnatpmp/libnatpmp.a \
	    ../third-party/libevent/.libs/libevent.a \
	    ../third-party/miniupnp/libminiupnp.a ../third-party/dht/libdht.a \
	    /usr/local/lib/libcurl.a $SSLROOT/lib/libssl.a \
	    $SSLROOT/lib/libcrypto.a -lrt -ldl -lz
    cd ../daemon
    gcc -o transmission-daemon daemon.o watch.o \
	    ../libtransmission/libtransmission.so.1 -lm
    gcc -o transmission-remote remote.o \
	    ../libtransmission/libtransmission.so.1 -lm
    cd ../cli
    gcc -o transmissioncli cli.o ../libtransmission/libtransmission.so.1 -lm
    cd ..
    strip -R .note -R .comment daemon/transmission-{daemon,remote} \
	    cli/transmissioncli libtransmission/libtransmission.so.1
    mkdir -p ../transmission-daemon/sbin ../transmission-{remote,cli}/bin \
	    ../libtransmission1/lib ../transmission-web/share/transmission
    cp daemon/transmission-daemon ../transmission-daemon/sbin/
    cp daemon/transmission-remote ../transmission-remote/bin/
    cp cli/transmissioncli ../transmission-cli/bin/
    cp libtransmission/libtransmission.so.1 ../libtransmission1/lib/
    tar -cf - -X - web << EOF | tar -C ../transmission-web/share/transmission/ \
	    -xf -
web/.svn
web/images/.svn
web/images/buttons/.svn
web/images/graphics/.svn
web/images/progress/.svn
web/javascript/.svn
web/javascript/jquery/.svn
web/stylesheets/.svn
web/LICENSE
web/javascript/jquery/jquery-1.3.2.js
web/javascript/jquery/jquery.contextmenu.r2.js
web/javascript/jquery/jquery.form-2.21.js
web/javascript/jquery/jquery.transmenu.js
web/javascript/jquery/json.js
EOF
    cd ..
    rm -rf transmission-1.76
}

[ -x ../openssl/build.sh ] && (cd ../openssl; ./build.sh)
(cd curl; ./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
