#! /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 xclass-0.9.2.tar.gz
    cd xclass-0.9.2
    ed -s lib/libxclass/Makefile.in >/dev/null <<EOF
/local\/xclass-icons/
s@local/xclass-icons@share/xclass/icons@
/usr\/local\/xclass/
s@/usr/local/xclass@@
w
q
EOF
    ed -s lib/libxclass/OXHtmlParse.cc >/dev/null <<EOF
/== -128/
s/-128/(char)-128/
1,\$s/(int) p,/(long int) p,/
w
q
EOF
    ed -s lib/libxclass/OXHtmlSizer.cc >/dev/null <<EOF
1,\$s/(int)p,/(long int)p,/
w
q
EOF
    ed -s test/ftest.cc >/dev/null <<EOF
/<fcntl.h>/a
#include <time.h>
.
w
q
EOF
    CXXFLAGS="$CXXFLAGS -fsigned-char" cflags_set=set ./configure \
	    --prefix=/usr/local --disable-opengl
    make
    sudo make -C config install
    sudo make -C include install
    sudo make -C lib install
    cd ..
    rm -rf xclass-0.9.2
}

while read FN; do
    eval "[ -e $FN ] || rebuild"
done < MANIFEST
