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

BUILD=`cpp -dumpmachine`
case "$BUILD" in
x86_64-linux-gnu)
    ARCH='amd64'
    ;;
*86-linux-gnu|i386-linux)
    ARCH='i386'
    ;;
powerpc-linux-gnu|ppc-linux-gnu)
    ARCH='powerpc'
    ;;
arm-linux-gnueabi)
    ARCH='armel'
    ;;
arm-linux-gnueabihf)
    ARCH='armhf'
    ;;
*)
    ARCH=`echo $BUILD | cut -f1 -d-`
    ;;
esac

rebuild () {
    tar xzf ipkg-0.99.163.tar.gz
    cd ipkg-0.99.163
    bunzip2 -c ../ipkg-0.99.163-dietpc-patch.bz2 | patch -p1 -b
    ./configure --prefix='' --sysconfdir=/etc --datadir=/lib --disable-shared \
	    --with-ipkglibdir=/var/lib --build=$BUILD
    for MAKEFILE in Makefile libbb/Makefile; do
	ed -s $MAKEFILE >/dev/null <<EOF
/^ALL_CFLAGS =/
s/-g -O/\$(CFLAGS)/
s/-DHOST_CPU_STR=[^[:blank:]]*/-DHOST_CPU_STR=\\\"$ARCH\\\"/
w
q
EOF
    done
    make
    strip -R .note -R .comment ipkg-cl
    mkdir -p ../ipkg/bin /usr/local/bin
    cp ipkg-cl ../ipkg/bin/ipkg
    sudo cp ipkg-cl /usr/local/bin/ipkg
    cd ..
    rm -rf ipkg-0.99.163
}

while read FN; do
    eval "[ -e $FN ] || rebuild"
done < MANIFEST

for CTRLFILE in ipkg/CONTROL/control ipkg/etc/ipkg.conf; do
    sed -i -e "s/__ARCH__/$ARCH/g" $CTRLFILE
    if [ $CTRLFILE = 'ipkg/etc/ipkg.conf' ]; then
	sudo cp ipkg/etc/ipkg.conf /etc/
    else
	sudo ipkg-build -o root -g root `dirname $CTRLFILE`/..
    fi
done
