#! /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 xjf iptables-1.4.10.tar.bz2
    cd iptables-1.4.10
    ./configure --prefix='' --enable-static --disable-shared
    # FIXME: needed to define __aligned_u64 (from <linux/types.h>) in
    # extensions/libxt_pkttype.c on Wheezy
    make
    strip -R .note -R .comment iptables-multi ip6tables-multi
    cp iptables-multi ../iptables/sbin/iptables
    cp ip6tables-multi ../ip6tables/sbin/ip6tables
    cd ..
    rm -rf iptables-1.4.10
}

mkdir -p iptables/sbin
ln -sf iptables iptables/sbin/iptables-restore
ln -sf iptables iptables/sbin/iptables-save
ln -sf iptables iptables/sbin/iptables-xml
mkdir -p ip6tables/sbin
ln -sf ip6tables ip6tables/sbin/ip6tables-restore
ln -sf ip6tables ip6tables/sbin/ip6tables-save

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
