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

rebuild () {
    tar xjf libaio-0.3.109.tar.bz2
    cd libaio-0.3.109/src
    ed -s Makefile 2>/dev/null <<EOF
/^CFLAGS :=/
s/-g -fomit-frame-pointer -O2/-fomit-frame-pointer $CFLAGS/
w
q
EOF
    make CC=gcc
    strip -R .note -R .comment libaio.so.1.0.1
    mkdir -p ../../libaio1/lib
    cp libaio.so.1.0.1 ../../libaio1/lib/libaio.so.1
    cd ../..
    rm -rf libaio-0.3.109
}

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
