#! /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: Should I prune back modules even further? (does anyone really use Targa,
# Sun Raster, etc?)

rebuild () {
    tar xJf gdk-pixbuf-2.26.4.tar.xz
    cd gdk-pixbuf-2.26.4
    ./configure --prefix=/usr/local --sysconfdir=/etc --localstatedir=/var \
	    --disable-nls --disable-rpath --enable-introspection=no \
	    --disable-gtk-doc-html --without-libtiff --without-libjasper \
	    --with-x11
    sed -i -e 's/^hardcode_into_libs=yes/hardcode_into_libs=no/' libtool
    make -C gdk-pixbuf
    make -C contrib
    strip -R .note -R .comment gdk-pixbuf/.libs/libgdk_pixbuf-2.0.so.0 \
	    gdk-pixbuf/.libs/libpixbufloader-*.so \
	    contrib/gdk-pixbuf-xlib/.libs/libgdk_pixbuf_xlib-2.0.so.0
    mkdir -p ../libgdk-pixbuf20-0/lib/gdk-pixbuf-2.0/2.10.0/loaders
    cp gdk-pixbuf/.libs/libgdk_pixbuf-2.0.so.0 \
	    contrib/gdk-pixbuf-xlib/.libs/libgdk_pixbuf_xlib-2.0.so.0 \
	    ../libgdk-pixbuf20-0/lib/
    cp gdk-pixbuf/.libs/libpixbufloader-*.so \
	    ../libgdk-pixbuf20-0/lib/gdk-pixbuf-2.0/2.10.0/loaders/
    sed 's@^"/.*/\([^/]\+\)\.la"$@"/usr/local/lib/gdk-pixbuf-2.0/2.10.0/loaders/\1.so"@'\
	gdk-pixbuf/loaders.cache >\
	../libgdk-pixbuf20-0/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache
    cd ..
    rm -rf gdk-pixbuf-2.26.4
}

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
