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

# FIXME: dependency on libnl.so, which Debian lacks a static library for!
# FIXME: src/drivers/driver_nl80211.c apparently includes a separate .config
#        in which CONFIG_LIBNL20=y.

rebuild () {
    tar xzf wpa_supplicant-1.1.tar.gz
    cd wpa_supplicant-1.1/wpa_supplicant
    cp defconfig .config
    ed -s .config >/dev/null << EOF
/^#CONFIG_DRIVER_NDISWRAPPER=y/
s/^#//
/^#CONFIG_DRIVER_IPW=y/
s/^#//
/^#CONFIG_DRIVER_RALINK=y/
s/^#//
/^#CONFIG_TLS=openssl/d
i
CONFIG_TLS=internal
.
/^#CONFIG_INTERNAL_LIBTOMMATH=y/
s/^#//
/^#CONFIG_INTERNAL_LIBTOMMATH_FAST=y/
s/^#//
\$a
CONFIG_LIBNL20=n
.
w
q
EOF
    make
    strip -R .note -R .comment wpa_supplicant wpa_passphrase
    mkdir -p ../../wpa-supplicant/sbin ../../wpa-passphrase/bin
    cp wpa_supplicant ../../wpa-supplicant/sbin/
    cp wpa_passphrase ../../wpa-passphrase/bin/
    cd ../..
    rm -rf wpa_supplicant-1.1
}

chmod 600 wpa-supplicant/etc/wpa_supplicant/wlan0.conf

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
