#! /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 openmotif-2.2.4.tar.gz
    cd openmotif-2.2.4
    AMVERS=`automake --version | awk '{print $NF; exit}' | cut -f1-2 -d.`
    for AMFILE in missing mkinstalldirs depcomp install-sh; do
	ln -sf /usr/share/automake-$AMVERS/$AMFILE
    done
    # For Wheezy:
    for LTFILE in config.sub config.guess ltmain.sh; do
	ln -sf /usr/share/libtool/config/$LTFILE
    done
    autoreconf
    ./configure --prefix=/usr --disable-static
    ed -s lib/Xm/Makefile >/dev/null <<EOF
/^libXm_la_LIBADD =/
s/-lXext //
w
q
EOF
    make -C lib/Xm
    strip -R .note -R .comment lib/Xm/.libs/libXm.so.3
    mkdir -p ../libxm3/lib
    cp lib/Xm/.libs/libXm.so.3 ../libxm3/lib/
    cd ..
    rm -rf openmotif-2.2.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
