#! /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 lm_sensors-3.3.3.tar.bz2
    cd lm_sensors-3.3.3
    make user PROG_EXTRA=sensord CFLAGS="$CFLAGS"
    strip -R .note -R .comment prog/sensors/sensors prog/sensord/sensord \
	    lib/libsensors.so.4
    mkdir -p ../sensors/bin ../sensord/sbin ../libsensors4/etc ../libsensors4/lib
    cp etc/sensors.conf.eg  ../libsensors4/etc/sensors.conf
    cp prog/sensors/sensors ../sensors/bin/
    cp prog/sensord/sensord ../sensord/sbin/
    cp lib/libsensors.so.4 ../libsensors4/lib/
    cd ..
    rm -rf lm_sensors-3.3.3
}

(cd rrdtool; ./build.sh)

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
