#! /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 grub-0.97.tar.gz
    cd grub-0.97
    gunzip -c ../grub_0.97-60.diff.gz | patch -p1
    sed -e '/^#/d' -e '/^$/d' debian/patches/00list | while read patch; do
    patch -p1 < debian/patches/$patch
    done
    ./configure --prefix='' --disable-auto-linux-mem-opt --without-curses
    make
    strip -R .note -R .comment grub/grub
    mkdir -p ../grub/sbin
    cp grub/grub ../grub/sbin/
    cp stage1/stage1 stage2/{stage2,e2fs_stage1_5,fat_stage1_5} \
	    ../grub-runtime/boot/grub/
    cd ..
    rm -rf grub-0.97
}

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

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
