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

# Bluez 4.x requires inotify support, which is not present in Etch headers
# and may or may not be supported by kernels of the era.

rebuild () {
    tar xzf bluez-utils-3.36.tar.gz
    cd bluez-utils-3.36
    ./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var \
	    --enable-hidd --enable-pand --enable-dund
    make -C common
    make -C hidd
    make -C pand
    make -C dund
    strip -R .note -R .comment hidd/hidd pand/pand dund/dund
    mkdir ../hidd/sbin ../pand/sbin ../dund/sbin
    cp hidd/hidd ../hidd/sbin/
    cp pand/pand ../pand/sbin/
    cp dund/dund ../dund/sbin/
    cd ..
    rm -rf bluez-utils-3.36
}

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
