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

rebuild () {
    # N.B. 1.1.11 no longer supports static greeter.
    tar xjf xdm-1.1.10.tar.bz2
    cd xdm-1.1.10
    ./configure --prefix=/usr --with-xdmlibdir=/etc/X11/xdm \
	    --with-xdmconfigdir=/etc/X11/xdm --with-xdmscriptdir=/etc/X11/xdm \
	    --disable-xpm-logos --disable-dynamic-greeter \
	    --without-xft --with-config-type=fs --without-pam \
	    --disable-silent-rules
    make xdm XDM_LIBS='-lXt -lXmu -lXinerama -lcrypt'
    make chooser CHOOSER_LIBS='/usr/lib/libXaw.so.6 -lXt -lXinerama'
    strip -R .note -R .commment xdm chooser
    mkdir -p ../xdm/bin ../xdm/lib/X11/xdm
    cp xdm ../xdm/bin/
    cp chooser ../xdm/lib/X11/xdm/
    cd ..
    rm -rf xdm-1.1.10
}

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
