#! /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 zenity-2.20.1.tar.gz
    cd zenity-2.20.1
    make
    cd src
    # For now, link statically to glade and canvas libraries.
    gcc -o zenity *.o /usr/lib/libglade-2.0.a /usr/lib/libgnomecanvas-2.a \
	    /usr/lib/arm-linux-gnueabi/libart_lgpl_2.a -lxml2 -lgtk-x11-2.0 \
	    -lgdk-x11-2.0 -lpangoft2-1.0 -lgdk_pixbuf-2.0 -lpango-1.0 \
	    -latk-1.0 /usr/lib/arm-linux-gnueabi/libgailutil.a
    strip -R .note -R .comment zenity
    cd ..
    mkdir -p ../zenity/bin ../zenity/share/zenity/clothes
    cp src/zenity ../zenity/bin/
    cp src/zenity.glade data/zenity-*.png ../zenity/share/zenity/
    cp data/{gnome-tshirt,hawaii-shirt,monk,sunglasses,surfboard}.png \
	    ../zenity/share/zenity/clothes/
    cd po
    for CATALOG in *.gmo; do
	LANG=`basename $CATALOG .gmo`
	mkdir -p ../../zenity/share/locale/$LANG/LC_MESSAGES
	cp $CATALOG ../../zenity/share/locale/$LANG/LC_MESSAGES/zenity.mo
    done
    cd ../..
    rm -rf zenity-2.20.1
}

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
