#! /bin/bash

trap "echo '*** BUILD FAILED! ***' 1>&2" ERR
set -ex -o pipefail
umask 022
export PATH='/bin:/usr/bin:/usr/local/bin'
export CFLAGS=${CFLAGS:--Os}
export CXXFLAGS=${CXXFLAGS:--Os}

rebuild () {
    tar xzf lloyd-yajl-1.0.12-0-g17b1790.tar.gz
    #tar xzf lloyd-yajl-2.0.1-0-gf4b2b1a.tar.gz
    cd lloyd-yajl-17b1790
    #cd lloyd-yajl-f4b2b1a
    sed -i -e 's/-O2//' CMakeLists.txt
    mkdir build
    cd build
    cmake ..
    make
    strip -R .note -R .comment yajl-1.0.12/lib/libyajl.so.1
    #strip -R .note -R .comment yajl-2.0.1/lib/libyajl.so.2
    mkdir -p ../../libyajl1/lib
    #mkdir -p ../../libyajl2/lib
    cp yajl-1.0.12/lib/libyajl.so.1 ../../libyajl1/lib/
    #cp yajl-2.0.1/lib/libyajl.so.2 ../../libyajl2/lib/
    cd ../..
    rm -rf lloyd-yajl-17b1790
    #rm -rf lloyd-yajl-f4b2b1a
}

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
