#! /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}

rebuild () {
    tar xjf syslinux-5.01.tar.bz2
    cd syslinux-5.01
    make clean
    make
    strip -R .note -R .comment linux/syslinux extlinux/extlinux
    mkdir -p ../syslinux/sbin ../extlinux/sbin \
	    ../syslinux-com32-{chain,menu,vesamenu}/boot/syslinux \
	    ../syslinux-com32-lib{com32,util}/boot/syslinux
    sudo cp utils/sha1pass linux/syslinux extlinux/extlinux /usr/local/bin/
    cp mbr/mbr.bin ../extlinux-runtime/boot/
    cp mbr/mbr.bin ../syslinux-runtime/boot/
    cp linux/syslinux ../syslinux/sbin/
    cp extlinux/extlinux ../extlinux/sbin/
    strip -R .note -R .comment com32/elflink/ldlinux/ldlinux.c32 com32/*/*.c32
    cp core/ldlinux.sys com32/elflink/ldlinux/ldlinux.c32 \
	    ../extlinux-runtime/boot/syslinux/
    cp core/ldlinux.sys com32/elflink/ldlinux/ldlinux.c32 \
	    ../syslinux-runtime/boot/syslinux/
    cp core/isolinux.bin com32/elflink/ldlinux/ldlinux.c32 \
	    ../isolinux-runtime/boot/syslinux/
    cp core/pxelinux.0 com32/elflink/ldlinux/ldlinux.c32 \
	    ../pxelinux-runtime/tftpboot/pxelinux/
    cp com32/lib/libcom32.c32 ../syslinux-com32-libcom32/boot/syslinux/
    cp com32/libutil/libutil.c32 \
	    ../syslinux-com32-libutil/boot/syslinux/
    cp com32/chain/chain.c32 ../syslinux-com32-chain/boot/syslinux/
    cp com32/mboot/mboot.c32 ../syslinux-com32-mboot/boot/syslinux/
    cp com32/menu/menu.c32 ../syslinux-com32-menu/boot/syslinux/
    cp com32/menu/vesamenu.c32 ../syslinux-com32-vesamenu/boot/syslinux/
    cd ..
    rm -rf syslinux-5.01
}

ARCH=`ipkg -V 0 print_architecture | tail -n 1 | cut -f2 -d' '`
[ "$ARCH" != 'i386' -a "$ARCH" != 'amd64' ] && exit 0

ln -sf syslinux extlinux-runtime/boot/extlinux
ln -sf syslinux isolinux-runtime/boot/isolinux
ln -sf syslinux pxelinux-runtime/tftpboot/pxelinux

while read FN; do
    eval "[ -e $FN ] || rebuild"
done < MANIFEST

for CTRLFILE in */CONTROL/control; do
    sed -i -e "s/__ARCH__/$ARCH/g" $CTRLFILE
    sudo ipkg-build -o root -g root `dirname $CTRLFILE`/..
done
