#! /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 () {
    mkdir -p libx11-6/lib/X11
    tar xjf rgb-1.0.5.tar.bz2 rgb-1.0.5/rgb.txt
    mv rgb-1.0.5/rgb.txt libx11-6/lib/X11/
    rmdir rgb-1.0.5

    tar xjf libX11-1.1.6.tar.bz2
    cd libX11-1.1.6
    ./configure --prefix=/usr --sysconfdir=/etc/X11 --localstatedir=/var \
	    --datadir=/usr/lib --disable-static --disable-ipv6 --without-xcb
    make
    strip -R .note -R .comment src/.libs/libX11.so.6
    mkdir -p ../libx11-6/lib/X11/locale/C ../libx11-6/lib/X11/locale/iso8859-1
    cp nls/C/{Compose,XI18N_OBJS,XLC_LOCALE} ../libx11-6/lib/X11/locale/C/
    cp nls/iso8859-1/{Compose,XI18N_OBJS,XLC_LOCALE} \
	    ../libx11-6/lib/X11/locale/iso8859-1/
    cp nls/compose.dir nls/locale.{dir,alias} ../libx11-6/lib/X11/locale/
    cp src/XKeysymDB ../libx11-6/lib/X11/
    cp src/.libs/libX11.so.6 ../libx11-6/lib/
    cd ..
    rm -rf libX11-1.1.6
}

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
