#! /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-libs-3.36.tar.gz
    cd bluez-libs-3.36
    ./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var \
	    --disable-static
    make
    strip -R .note -R .comment src/.libs/libbluetooth.so.2
    mkdir -p ../libbluetooth2/lib
    cp src/.libs/libbluetooth.so.2 ../libbluetooth2/lib/
    cd ..
    rm -rf bluez-libs-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
