#! /bin/bash

trap "echo '*** BUILD FAILED! ***' 1>&2" ERR
set -ex -o pipefail
umask 022
export PATH='/bin:/usr/bin:/usr/local/bin'
export CFLAGS=${CFLAGS:--Os}
export CXXFLAGS=${CXXFLAGS:--Os}

KVER='2.6.35'
POSTPATCH='14'
BUILD='1'

rebuild () {
    tar xjf linux-$KVER.tar.bz2
    mv linux-$KVER linux-$KVER.$POSTPATCH-$TGT
    cd linux-$KVER.$POSTPATCH-$TGT
    bunzip2 -c ../patch-$KVER.$POSTPATCH.bz2 | patch -p1 -E
    gunzip -c ../unionfs-*_for_$KVER.*.diff.gz | patch -p1 -E
    gunzip -c ../kernel-image-$TGT/boot/config*.gz >.config
    make oldconfig >/dev/null
    make
    cp $KIMAGE ../kernel-image-$TGT/boot/`basename \
	    $KIMAGE`-$KVER.$POSTPATCH-$BUILD-$TGT
    ln -sf `basename $KIMAGE`.$KVER.$POSTPATCH-$BUILD-$TGT \
	    ../kernel-image-$TGT/boot/vmlinuz
    cp System.map \
	    ../kernel-image-$TGT/boot/System.map-$KVER.$POSTPATCH-$BUILD-$TGT
    gzip -9f ../kernel-image-$TGT/boot/System.map-$KVER.$POSTPATCH-$BUILD-$TGT
    cp .config ../kernel-image-$TGT/boot/config-$KVER.$POSTPATCH-$BUILD-$TGT
    gzip -9f ../kernel-image-$TGT/boot/config-$KVER.$POSTPATCH-$BUILD-$TGT
    make modules_install INSTALL_MOD_PATH=../kernel-modules-$TGT/
    rm ../kernel-modules-$TGT/lib/$KVER.$POSTPATCH-$BUILD-$TGT/* 2>/dev/null
    find ../kernel-modules-$TGT/lib/$KVER.$POSTPATCH-$BUILD-$TGT/modules \
	    -name \*.ko -exec gzip -9 {} \;
    # FIXME: need busybox here!
    ../../busybox/busybox/bin/busybox depmod -AeF System.map -b \
	    ../kernel-modules-$TGT $KVER.$POSTPATCH-$BUILD-$TGT
    cd ..
#   rm -rf linux-$KVER.$POSTPATCH-$TGT
}

ARCH=`ipkg -V 0 print_architecture | tail -n 1 | cut -f2 -d' '`
KIMAGE='arch/$ARCH/boot/zImage'
case "$ARCH" in
powerpc)
    TGTLIST='qemu-g3beige'
    ;;
arm|armel)
    TGTLIST='qemu-versatile'
    KIMAGE='arch/arm/boot/zImage'
    ;;
mips|mipsel)
    TGTLIST='qemu-malta'
    ;;
sparc)
    TGTLIST='qemu-sparc32'
    ;;
i386)
    TGTLIST='vmguest 586 686'
    KIMAGE='arch/x86/boot/bzImage'
    ;;
amd64)
    TGTLIST='vmguest-x64 x64'
    KIMAGE='arch/x86_64/boot/bzImage'
    ;;
esac

# FIXME: need to do this better!

#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
