#! /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 xjf font-adobe-75dpi-1.0.3.tar.bz2
    cd font-adobe-75dpi-1.0.3
    ./configure --prefix=/usr --sysconfdir=/etc/X11 --localstatedir=/var \
	    --datadir=/usr/lib
    make helvB12-ISO8859-1.pcf.gz
    mkdir -p ../xfonts-minimal/lib/X11/fonts/75dpi
    bdftopcf helvB12-ISO8859-1.bdf | gzip -9 >\
	    ../xfonts-minimal/lib/X11/fonts/75dpi/helvB12-ISO8859-1.pcf.gz
    cd ..
    rm -rf font-adobe-75dpi-1.0.3

    tar xjf font-misc-misc-1.1.2.tar.bz2
    cd font-misc-misc-1.1.2
    ./configure --prefix=/usr --sysconfdir=/etc/X11 --localstatedir=/var \
	    --datadir=/usr/lib
    make 7x14-ISO8859-1.pcf.gz
    mkdir -p ../xfonts-minimal/lib/X11/fonts/misc
    bdftopcf 7x14-ISO8859-1.bdf | gzip -9 >\
	    ../xfonts-minimal/lib/X11/fonts/misc/7x14-ISO8859-1.pcf.gz
    cd ..
    rm -rf font-misc-misc-1.1.2

    tar xjf font-cursor-misc-1.0.3.tar.bz2
    cd font-cursor-misc-1.0.3
    ./configure --prefix=/usr --sysconfdir=/etc/X11 --localstatedir=/var \
	    --datadir=/usr/lib
    make cursor.pcf.gz
    bdftopcf cursor.bdf | gzip -9 >\
	    ../xfonts-minimal/lib/X11/fonts/misc/cursor.pcf.gz
    cd ..
    rm -rf font-cursor-misc-1.0.3

    cat >xfonts-minimal/lib/X11/fonts/75dpi/fonts.alias <<EOF
variable	-*-helvetica-bold-r-normal-*-*-120-*-*-*-*-iso8859-1
EOF
    cat >xfonts-minimal/lib/X11/fonts/misc/fonts.alias <<EOF
fixed		-misc-fixed-medium-r-normal--14-130-75-75-c-70-iso8859-1
7x14		-misc-fixed-medium-r-normal--14-130-75-75-c-70-iso8859-1
EOF
    mkfontscale -b -s -l xfonts-minimal/lib/X11/fonts/{75dpi,misc}
}

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
