#! /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}

# FIXME: What are libgail.so and libferret.so for?  Do we need them?
# FIXME: Strongly suspect bogus dependencies due to sloppy linking.
#        Care factor?

rebuild () {
    tar xJf gtk+-2.24.17.tar.xz
    cd gtk+-2.24.17
    ./configure --prefix=/usr/local --sysconfdir=/etc --localstatedir=/var \
	    --disable-cups --enable-introspection=no --disable-gtk-doc-html \
	    --with-xinput=yes --with-x
    make
    strip -R .note -R .comment gdk/.libs/libgdk-x11-2.0.so.0 \
	    gtk/.libs/libgtk-x11-2.0.so.0 modules/input/.libs/*.so \
	    modules/*/*/.libs/*.so
    mkdir -p ../libgtk20-0/lib/gtk-2.0/2.10.0/{engines,immodules,printbackends}
    cp gdk/.libs/libgdk-x11-2.0.so.0 gtk/.libs/libgtk-x11-2.0.so.0 \
	    ../libgtk20-0/lib/
    cp modules/input/.libs/*.so ../libgtk20-0/lib/gtk-2.0/2.10.0/immodules/
    sed -e 's@^"/.*/\([^/]\+\)\.la"@"/usr/local/lib/gtk-2.0/2.10.0/immodules/\1.so"@' \
	    -e '/^#/d' modules/input/gtk.immodules >\
	    ../libgtk20-0/lib/gtk-2.0/2.10.0/gtk.immodules
    cp modules/engines/*/.libs/*.so \
	    ../libgtk20-0/lib/gtk-2.0/2.10.0/engines/
    cp modules/printbackends/*/.libs/*.so \
	    ../libgtk20-0/lib/gtk-2.0/2.10.0/printbackends/
    #mkdir -p ../libgtk20-0/share/themes/{Default,Emacs}/gtk-2.0-key \
    #	    ../libgtk20-0/share/themes/Raleigh/gtk-2.0
    # There doesn't seem to be any point in doing these:
    #cp gtk/gtkrc.key.default \
    #	    ../libgtk20-0/share/themes/Default/gtk-2.0-key/gtkrc
    #cp gtk/gtkrc.default ../libgtk20-0/share/themes/Raleigh/gtk-2.0/gtkrc
    # The usefulness of this keybinding is dubious!
    #cp gtk/gtkrc.key.emacs ../libgtk20-0/share/themes/Emacs/gtk-2.0-key/gtkrc
    cd po
    for CATALOG in *.gmo; do
	LANG=`basename $CATALOG .gmo`
	mkdir -p ../../libgtk20-i18n/share/locale/$LANG/LC_MESSAGES
	cp $CATALOG ../../libgtk20-i18n/share/locale/$LANG/LC_MESSAGES/gtk20.mo
    done
    cd ../po-properties
    for CATALOG in *.gmo; do
	LANG=`basename $CATALOG .gmo`
	mkdir -p ../../libgtk20-i18n/share/locale/$LANG/LC_MESSAGES
	cp $CATALOG \
	../../libgtk20-i18n/share/locale/$LANG/LC_MESSAGES/gtk20-properties.mo
    done
    cd ../..
    #rm -rf gtk+-2.24.17
}

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
