#! /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-kvm-1.2.0.tar.gz
    cd qemu-kvm-1.2.0
    bunzip2 -c ../qemu-kvm-1.2.0-dietpc-patch.bz2 | patch -p1 -b
    ./configure --prefix=/usr/local --sysconfdir=/etc --disable-linux-user \
	    --disable-uuid --disable-curses --disable-vnc-tls --disable-werror \
	    --disable-debug-info --disable-vnc-png --disable-curl \
	    --enable-virtfs --enable-bluez --enable-linux-aio --enable-mixemu \
	    --enable-system --enable-sdl --enable-spice --enable-kvm \
	    --disable-libiscsi --disable-xen --audio-drv-list="oss sdl" \
	    --audio-card-list='ac97 es1370 sb16 cs4231a adlib gus hda' \
	    --target-list="i386-softmmu x86_64-softmmu"
    sed -i -e 's@-lgthread-2.0 -lrt -lglib-2.0@-lrt /usr/lib/libglib-2.0.a /usr/lib/libgthread-2.0.a@' config-host.mak
    sed -i -e 's@ -lpci @ /usr/lib/libpci.a @' -e 's/-lglib-2.0 / /' \
	    -e 's/-lpixman-1 -lcelt051 / /' \
	    -e 's@-lbluetooth@/usr/lib/libbluetooth.so.3@' \
	    i386-softmmu/config-target.mak
    sed -i -e 's@ -lpci @ /usr/lib/libpci.a @' -e 's/-lglib-2.0 / /' \
	    -e 's/-lpixman-1 -lcelt051 / /' \
	    -e 's@-lbluetooth@/usr/lib/libbluetooth.so.3@' \
	    x86_64-softmmu/config-target.mak
    make
    strip -R .note -R .comment i386-softmmu/qemu-system-i386 \
	    x86_64-softmmu/qemu-system-x86_64
    upx -9 i386-softmmu/qemu-system-i386 x86_64-softmmu/qemu-system-x86_64
    mkdir -p ../qemu-i386/bin ../qemu-x86-64/bin
    cp i386-softmmu/qemu-system-i386 ../qemu-i386/bin/
    cp x86_64-softmmu/qemu-system-x86_64 ../qemu-x86-64/bin/
    mkdir -p ../qemu-roms-x86/share/qemu
    cp pc-bios/bios.bin pc-bios/sgabios.bin pc-bios/optionrom/*.bin \
	    pc-bios/pxe-*.rom ../qemu-roms-x86/share/qemu/
    chmod 644 ../qemu-roms-x86/share/qemu/*
    cd ..
    rm -rf qemu-kvm-1.2.0
}

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
