#! /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 qvwm-1.1.12-10-IKu.tar.gz
    cd qvwm-1.1.12-10-IKu
    bunzip2 -c ../qvwm-1.1.12-9-IKu-timer-patch.bz2 | patch -p1 -b
    ./configure --prefix=/usr --without-alsa --without-esd --without-imlib \
	    --with-qvwmdir=/etc/qvwm --with-snddir=/usr/share/qvwm/sounds \
	    --with-imgdir=/usr/share/qvwm/images --disable-xsmp
    ed -s src/pixmap_image.cc >/dev/null <<EOF
/X11\/Xutil.h/a
#include <X11/xpm.h>
.
w
q
EOF
    ed -s src/Makefile >/dev/null <<EOF
/^LIBS =/
s/\$/ -lXpm/
w
q
EOF
    make
    cd src
    gcc -o qvwm *.o -lXext -lX11 -lXpm -Wl,-Bstatic -lXss -lstdc++ \
	    -Wl,-Bdynamic -static-libgcc
    strip -R .note -R .comment qvwm
    mkdir -p ../../qvwm/bin
    cp qvwm ../../qvwm/bin/
    cd ../..
    rm -rf qvwm-1.1.12-10-IKu
}

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
