#! /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 xkeyboard-config-2.1.tar.bz2
    tar xjf xkbdata-1.0.1.tar.bz2
    cd xkbdata-1.0.1
#    cd xkeyboard-config-2.1
    ./configure --prefix=/usr --sysconfdir=/etc/X11 --localstatedir=/var \
	    --datadir=/usr/lib
#    ./configure --prefix=/usr --sysconfdir=/etc/X11 --localstatedir=/var \
#	    --datadir=/usr/lib --disable-nls --enable-compat-rules \
#	    --with-xkb-rules-symlink=Xorg
    make
    ENDIAN=`echo -e "#include <endian.h>\n[ __BYTE_ORDER = __LITTLE_ENDIAN ] \
	    && echo little || echo big\n" | cpp -E -pipe | sh`
    for KM_INDEX in keymap/xfree86 keymap/macintosh; do
	for KEYMAP in `grep -w 'xkb_keymap' $KM_INDEX | cut -f2 -d \"`; do
	    KM_HYPHEN=`echo $KEYMAP | tr '[A-Z_]' '[a-z\-]'`
	    mkdir -p ../xkbmap-$KM_HYPHEN-$ENDIAN/CONTROL \
		    ../xkbmap-$KM_HYPHEN-$ENDIAN/etc/rc.d \
		    ../xkbmap-$KM_HYPHEN-$ENDIAN/etc/X11/xkb/precompiled
	    sed -e "s/__KM_USCORE__/$KEYMAP/g" \
		    -e "s/__KM_HYPHEN__/$KM_HYPHEN/g" \
		    -e "s/__ENDIAN__/$ENDIAN/g" ../control_template \
			    >../xkbmap-$KM_HYPHEN-$ENDIAN/CONTROL/control
	    sed -e "s/__KM_USCORE__/$KEYMAP/g" \
		    -e "s/__KM_HYPHEN__/$KM_HYPHEN/g" \
		    -e "s/__ENDIAN__/$ENDIAN/g" ../rc_template >\
		    ../xkbmap-$KM_HYPHEN-$ENDIAN/etc/rc.d/xkbmap-$KM_HYPHEN-$ENDIAN
	    chmod 755 ../xkbmap-$KM_HYPHEN-$ENDIAN/etc/rc.d/xkbmap-$KM_HYPHEN-$ENDIAN
	    xkbcomp -I. -dflts -xkm -m $KEYMAP $KM_INDEX \
		    ../xkbmap-$KM_HYPHEN-$ENDIAN/etc/X11/xkb/precompiled/$KEYMAP-$ENDIAN.xkm 2>/dev/null
	done
    done
# FIXME: rules/base
    cd ..
    rm -rf xkbdata-1.0.1
#    rm -rf xkeyboard-config-2.1
    echo >done
}

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
