#! /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 Xaw95-1.1-src.tar.gz
    cd Xaw95-1.1
    gunzip -c ../Xaw95-1.1-dietpc-patch.gz | patch -p1 -b
    if [ -d /usr/include/X11/Xaw3d -a ! -L /usr/include/X11/Xaw3d ]; then
	sudo mv /usr/include/X11/Xaw3d /usr/include/X11/Xaw3d.orig
    fi
    sudo ln -sf `pwd` /usr/include/X11/Xaw3d
    xmkmf
    make includes
    make depend
    make CDEBUGFLAGS="$CFLAGS -fno-strict-aliasing" CLIBDEBUGFLAGS= \
	    SOXAWREV=6.0 XPMLIB= SMLIB= ICELIB= EXTENSIONLIB=
    gcc -o libXaw.so.7 -shared libXaw.so.6
    strip -R .note -R .comment libXaw.so.6 libXaw.so.7
    mkdir -p ../libxaw6/lib ../libxaw7-fake/lib
    cp libXaw.so.6 ../libxaw6/lib/
    cp libXaw.so.7 ../libxaw7-fake/lib/
    cd ..
    rm -rf Xaw95-1.1

    sudo rm -f /usr/include/X11/Xaw3d
    if [ -d /usr/include/X11/Xaw3d.orig ]; then
	sudo mv /usr/include/X11/Xaw3d.orig /usr/include/X11/Xaw3d
    fi
}

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
