#! /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 console-data_1999.08.29.orig.tar.gz
    cd console-data-1999.08.29
    mkdir -p ../console-data-us/lib/kbd/consolefonts
    cp consolefonts/default8x16.psf  ../console-data-us/lib/kbd/consolefonts/
    cd keymaps/i386
    # FIXME: check that busybox exists and has dumpkmap applet
    for kmap in `find . -name \*.kmap -print`; do
	sudo loadkeys $kmap
	sudo busybox dumpkmap >`echo $kmap | sed 's/kmap$/bkmap/'`
    done
    sudo loadkeys -d
    # FIXME
#   mkdir -p ~/diet-pc/shell/extras/kmaps
#   find .  -name \*.bkmap -print | tar cTf - - | tar xCf \
#	    ~/diet-pc/shell/extras/kmaps -
    mkdir -p ../../../console-data-us/lib/kbd/kmaps
    cp qwerty/us.bkmap ../../../console-data-us/lib/kbd/kmaps/
    cd ../../..
    rm -rf console-data-1999.08.29
}

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
