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

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

rebuild () {
    tar xzf opkg-0.1.8.tar.gz
    cd opkg-0.1.8
    ./configure --prefix='' --sysconfdir=/etc --datadir=/lib --disable-shared \
	    --disable-gpg --disable-curl --with-opkglibdir=/var/lib \
	    --build=$BUILD
    for MAKEFILE in Makefile libbb/Makefile; do
	ed -s $MAKEFILE >/dev/null <<EOF
/^ALL_CFLAGS =/
s/-g -O/\$(CFLAGS)/
w
q
EOF
    done
    ed -s libopkg/Makefile >/dev/null <<EOF
/^AM_CFLAGS =/
s/-DHOST_CPU_STR=[^[:blank:]]*/-DHOST_CPU_STR=\\\"$ARCH\\\"/
w
q
EOF
    make
    strip -R .note -R .comment src/opkg-cl
    mkdir -p ../opkg/bin
    cp src/opkg-cl ../opkg/bin/opkg
    sudo cp src/opkg-cl /usr/local/bin/opkg
    cd ..
    rm -rf opkg-0.1.8
}

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

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