#! /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 dropbear-2013.58.tar.bz2
    cd dropbear-2013.58
    # Fixed in 2012.55
    #bunzip2 -c ../dropbear-2011.54-dietpc-patch.bz2 | patch -p1 -b
    ./configure --prefix='' --enable-bundled-libtom
    ed -s options.h >/dev/null <<EOF
/^#define XAUTH_COMMAND /
s@X11/@@
/^#define SFTPSERVER_PATH /
s@^\(.*\)\$@/\* \1 \*/@
/^#define _PATH_SSH_PROGRAM /
s@usr/@@
/^#define DEFAULT_PATH /d
i
#define DEFAULT_PATH "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin"
.
w
q
EOF
    make
    make scp
    strip -R .note -R .comment dropbear dropbearconvert dropbearkey dbclient \
	    scp
    mkdir -p ../dropbear/sbin ../dropbear-utils/bin
    cp dropbear scp ../dropbear/sbin/
    cp dbclient scp ../dbclient/bin/
    cp dropbearconvert dropbearkey ../dropbear-utils/bin/ 
    cd ..
    rm -rf dropbear-2013.58
}

chmod 0600 dropbear/etc/dropbear/*
mkdir -p dbclient/bin
ln -sf dbclient dbclient/bin/ssh

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
