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

# N.B. Wheezy limited to pango <= 1.30.x due to minimum glib2.0 requirement.

# FIXME: Is libthai necessary?
# FIXME: Should I compile in pango-basic-fc and pango-basic-x, and provide all
# loadable modules in a separate package?

rebuild () {
    tar xJf pango-1.30.1.tar.xz
    cd pango-1.30.1
    ./configure --prefix=/usr/local --sysconfdir=/etc --localstatedir=/var \
	    --enable-debug=no --enable-introspection=no \
	    --enable-gtk-doc-html=no
    sed -i -e 's/^hardcode_into_libs=yes/hardcode_into_libs=no/' libtool
    make -C pango
    make -C modules
    strip -R .note -R .comment pango/.libs/libpango*-1.0.so.0 \
	    pango/.libs/pango-querymodules modules/*/.libs/*.so
    mkdir -p ../libpango10-0/lib/pango/1.6.0/modules ../libpango10-0/etc/pango
    cp pango/.libs/libpango*-1.0.so.0 ../libpango10-0/lib/
    cp modules/*/.libs/*.so ../libpango10-0/lib/pango/1.6.0/modules/
    # FIXME: This doesn't work, had to use pango-querymodules instead.
    #sed -e 's@^.*/\([^/]\+\).la\>@/usr/local/lib/pango/1.6.0/modules/\1.so@' \
    #	    modules/pango.modules > ../libpango10-0/etc/pango/pango.modules
    cd ..
    rm -rf pango-1.30.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
