#! /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 libtirpc-0.2.2.tar.bz2
    cd libtirpc-0.2.2
    bunzip2 -c ../libtirpc-0.2.2-remove-nis-2.patch.bz2 | patch -p1 -b
    bunzip2 -c ../libtirpc-0.2.2-no-sockcloexec.patch.bz2 | patch -p1 -b
    sh autogen.sh
    ./configure --prefix=/usr/local --disable-gss --disable-static
    make
    # Install everything except manpages (on < Squeeze)
    # Debian's /etc/netconfig will get clobbered, but that's OK as content is
    # exactly the same anyway.
    #sudo make install SUBDIRS='src doc'
    strip -R .note -R comment src/.libs/libtirpc.so.1
    mkdir -p ../libtirpc1/etc ../libtirpc1/lib
    cp doc/etc_netconfig ../libtirpc1/etc/netconfig
    cp src/.libs/libtirpc.so.1 ../libtirpc1/lib/
    cd ..
    rm -rf libtirpc-0.2.2
}

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
