#! /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 xine-ui-0.99.5.tar.gz
    cd xine-ui-0.99.5
    # 0.99.7 doesn't grok --with-xine-prefix
    PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/local/lib/pkgconfig ./configure \
	    --prefix=/usr/local --with-xine-prefix=/usr/local --disable-xft \
	    --without-curl
    # Suggestion for 0.99.7: change br_fontname in src/xitk/common.h from
    # -misc-fixed-medium-r-normal-10 to -misc-fixed-medium-r-normal-14.
    make
    cd src/xitk
    gcc -o xine-remote xine_remote-network.o ../common/libcommon.a \
	    -Wl,-Bstatic -lreadline -ltermcap -Wl,-Bdynamic -lpthread
    # 0.99.7 also needs Xss (static) and jpeg (dynamic)
    gcc -o xine `ls *.o | grep -v xine_remote` \
	    ../common/libcommon.a xine-toolkit/libxitk.a oxine/liboxine.a \
	    Imlib-light/libImlib-light.a ../common/libcommonx.a -lxine -lpng \
	    -Wl,-Bstatic -llirc_client -lXxf86vm -lXtst -Wl,-Bdynamic -lz -lm \
	    -lpthread -ldl -lX11 -lXext -lXv -lXinerama
    cd ../fb
    gcc -o fbxine *.o ../common/libcommon.a -Wl,-Bstatic -lncurses \
	    -llirc_client -Wl,-Bdynamic -lxine
    cd ../..
    # FIXME: is this necessary?
    sudo make install
    sudo strip -R .note -R .comment /usr/local/bin/{fbxine,xine,xine-remote}
    mkdir -p ../xine/bin ../xine/share/doc/xine-ui ../xine/share/xine/skins
    cp /usr/local/bin/xine ../xine/bin/
    cp /usr/local/share/doc/xine-ui/README.en.* ../xine/share/doc/xine-ui/
    # Changed in 0.99.7 to a png file, can substitute mpv file in
    # misc/splash-default before running configure.
    cp /usr/local/share/xine/skins/xine-ui_logo.mpv  ../xine/share/xine/skins/
    cd ..
    rm -rf xine-ui-0.99.5
    tar -C xine/share/xine/skins -xz --exclude=cloudy/font_install.sh \
	    --exclude=cloudy/doinst.sh -f cloudy.tar.gz
}

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
