#! /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 xzf wuftpd-cvs-20080208.tar.gz
    cd wu-ftpd
    ./configure --prefix=/usr --disable-private --enable-anononly \
	    --disable-pam --disable-log-rp --disable-virtual --disable-mail \
	    --enable-badclients --enable-rfc931
    ed -s config.h >/dev/null <<EOF
/#undef LIBWRAP/d
i
#define LIBWRAP 1
.
w
q
EOF
    ed -s src/Makefile >/dev/null <<EOF
/^LIBS=/
s/\$/ -lwrap/
w
q
EOF
    make -C support
    make -C src ftpd
    strip -R .note -R .comment src/ftpd
    mkdir -p ../anon-ftpd/sbin
    cp src/ftpd ../anon-ftpd/sbin/in.ftpd
    cd ..
    rm -rf wu-ftpd
}

chmod 600 anon-ftpd/etc/ftpaccess

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
