#! /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'
# Optimization is important for this package - override usual "-Os" setting.
export CFLAGS="`echo ${CFLAGS:--O3} | sed 's/-Os/-O3/'`"
export CXXFLAGS="`echo ${CXXFLAGS:--O3} | sed 's/-Os/-O3/'`"

rebuild () {
    tar xzf qemu-1.0.1.tar.gz
    cd qemu-1.0.1
    bunzip2 -c ../qemu-1.0-dietpc-patch.bz2 | patch -p1 -b
    ./configure --prefix=/usr/local --sysconfdir=/etc --disable-linux-user \
	    --disable-uuid --disable-attr --disable-curses --disable-vnc-tls \
	    --disable-vnc-png --disable-curl --disable-spice --enable-bluez \
	    --enable-vnc-thread --enable-mixemu --enable-system --enable-sdl \
	    --disable-kvm --disable-smartcard --audio-drv-list='oss sdl' \
	    --enable-linux-aio --disable-libiscsi --disable-xen \
	    --audio-card-list='ac97 es1370 sb16 cs4231a adlib gus hda' \
	    --target-list="arm-softmmu mips-softmmu mipsel-softmmu ppc-softmmu \
	    sparc-softmmu"
    for CTMAK in */config-target.mak; do
	sed -i -e 's/-lglib-2.0 / /' -e \
		's@-lbluetooth@/usr/lib/libbluetooth.so.3@' $CTMAK
    done
    sed -i 's@-lgthread-2.0 -lrt -lglib-2.0@-lrt /usr/lib/libglib-2.0.a /usr/lib/libgthread-2.0.a@' config-host.mak
    make
    strip -R .note -R .comment qemu-img *-softmmu/qemu-system-*
    # FIXME: upx -9 *-softmmu/qemu-system-*?
    mkdir -p ../qemu-img/bin
    cp qemu-img ../qemu-img/bin/
    for ARCH in arm mips mipsel ppc sparc; do
	mkdir -p ../qemu-$ARCH/bin
	cp $ARCH-softmmu/qemu-system-$ARCH ../qemu-`echo $ARCH | tr _ -`/bin/
    done
    mkdir -p ../qemu-keymaps/share/qemu/keymaps
    cp pc-bios/keymaps/* ../qemu-keymaps/share/qemu/keymaps/
    mkdir -p ../qemu-roms-vga/share/qemu/
    cp pc-bios/vgabios*.bin ../qemu-roms-vga/share/qemu/
    mkdir -p ../qemu-roms-ppc/share/qemu
    cp pc-bios/ppc_rom.bin pc-bios/openbios-ppc ../qemu-roms-ppc/share/qemu/
    mkdir -p ../qemu-roms-sparc/share/qemu
    cp pc-bios/openbios-sparc32 ../qemu-roms-sparc/share/qemu/
    cd ..
    rm -rf qemu-1.0.1
}

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
