#! /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 openbox-3.5.0.tar.gz
    cd openbox-3.5.0
    ./configure --prefix=/usr/local --sysconfdir=/etc --localstatedir=/var \
	    --disable-shared --enable-static --disable-rpath --disable-imlib2 \
	    --disable-startup-notification --disable-session-management
    make
    # Libtool linking is a total mess, so we do it ourselves without the bogus
    # dependencies and shared libraries we asked not to have!
    # libxrender1 and libz1
    gcc -o openbox/openbox openbox/*.o openbox/*/*.o \
	obrender/.libs/libobrender.a obt/.libs/libobt.a -lX11 -lSM -lICE \
	-lXext -lXinerama -lXrandr -lXcursor -lxml2 -lglib-2.0 -lpango-1.0 \
	-lpangoft2-1.0 -lpangoxft-1.0
    strip -R .note -R .coment openbox/openbox
    mkdir -p ../openbox/bin
    cp openbox/openbox ../openbox/bin/
    mkdir -p ../openbox/etc/xdg/openbox
    # FIXME: Both of these will have to be customised
    cp data/*.xml ../openbox/etc/xdg/openbox/
    mkdir -p ../openbox/share/themes ../openbox-themes/share
    tar -c -f - themes | tar -C ../openbox-themes/share/ -xf -
    mv ../openbox-themes/share/themes/Clearlooks ../openbox/share/themes/
    cd po
    for CATALOG in *.gmo; do
	LANG=`basename $CATALOG .gmo`
	mkdir -p ../../openbox-i18n/share/locale/$LANG/LC_MESSAGES
        cp $CATALOG \
		../../openbox-i18n/share/locale/$LANG/LC_MESSAGES/openbox.mo
    done
    cd ../..
    rm -rf openbox-3.5.0
}

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
