#! /bin/bash

trap "echo '*** BUILD FAILED! ***' 1>&2" ERR
set -ex -o pipefail
umask 022
export PATH='/bin:/usr/bin:/usr/local/bin:~/diet-pc/tools'
export CFLAGS=${CFLAGS:--Os}
export CXXFLAGS=${CXXFLAGS:--Os}

rebuild () {
    tar xzf gtk+-1.2.10.tar.gz
    cd gtk+-1.2.10
    # config.sub is too old for amd64 et al, can't run autoreconf due to age
    # of configure.in, so selectively update automake files.
    AMVERS=`automake --version | awk '{print $NF; exit}' | cut -f1-2 -d.`
    for FILE in config.guess config.sub install-sh missing; do
        cp /usr/share/automake-$AMVERS/$FILE .
    done
    cp /usr/share/libtool/config/ltmain.sh .
    ./configure --prefix=/usr/local --sysconfdir=/etc --localstatedir=/var \
	    --with-xinput=xfree --disable-nls
    # GTK+ 1.x not available for Wheezy, so install to /usr/local:
    cp /usr/bin/libtool .
    sudo make install
    strip -R .note -R .comment gtk/.libs/libgtk-1.2.so.0 \
	    gdk/.libs/libgdk-1.2.so.0
    mkdir -p ../libgtk12-0/lib
    cp gtk/.libs/libgtk-1.2.so.0 gdk/.libs/libgdk-1.2.so.0 ../libgtk12-0/lib/
    cp gtk/gtkrc.[a-z][a-z]* ../libgtk12-0/etc/gtk/
    cd ..
    rm -rf gtk+-1.2.10
}

mkdir -p libgtk12-0/etc/gtk
ln -sf gtkrc.cp1251 libgtk12-0/etc/gtk/gtkrc.be
ln -sf gtkrc.cp1251 libgtk12-0/etc/gtk/gtkrc.bg
ln -sf gtkrc.iso-8859-5 libgtk12-0/etc/gtk/gtkrc.bg_BG.iso88595
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.cs
ln -sf gtkrc.iso-8859-14 libgtk12-0/etc/gtk/gtkrc.cy
ln -sf gtkrc.iso-8859-15 libgtk12-0/etc/gtk/gtkrc.et
ln -sf gtkrc.iso-8859-14 libgtk12-0/etc/gtk/gtkrc.ga
ln -sf gtkrc.cp1255 libgtk12-0/etc/gtk/gtkrc.ga
ln -sf gtkrc.cp1255 libgtk12-0/etc/gtk/gtkrc.he_IL.cp1255
ln -sf gtkrc.cp1255 libgtk12-0/etc/gtk/gtkrc.he_IL.microsoftcp1255
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.hr
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.hu
ln -sf gtkrc.ka_GE.georgianps libgtk12-0/etc/gtk/gtkrc.ka
ln -sf gtkrc.iso-8859-13 libgtk12-0/etc/gtk/gtkrc.lt
ln -sf gtkrc.iso-8859-13 libgtk12-0/etc/gtk/gtkrc.lv
ln -sf gtkrc.iso-8859-13 libgtk12-0/etc/gtk/gtkrc.mi
ln -sf gtkrc.iso-8859-5 libgtk12-0/etc/gtk/gtkrc.mk
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.pl
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.ro
ln -sf gtkrc.iso-8859-5 libgtk12-0/etc/gtk/gtkrc.ru_RU.iso88595
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.sk
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.sl
ln -sf gtkrc.iso-8859-5 libgtk12-0/etc/gtk/gtkrc.sp
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.sq
ln -sf gtkrc.iso-8859-2 libgtk12-0/etc/gtk/gtkrc.sr
ln -sf gtkrc.vi_VN.tcvn libgtk12-0/etc/gtk/gtkrc.vi
ln -sf gtkrc.vi_VN.viscii libgtk12-0/etc/gtk/gtkrc.vi_VN.viscii111
ln -sf gtkrc.cp1255 libgtk12-0/etc/gtk/gtkrc.yi

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
