#! /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 xjf apr-util-1.3.12.tar.bz2
    cd apr-util-1.3.12
    #bunzip2 -c ../apr-util-1.3.12-lenny-compat-patch.bz2 | patch -p1 -b
    sed -i -e "s/CFLAGS=\".*-O2.*\"/CFLAGS=\"$CFLAGS\"/" configure
    ./configure --prefix=/usr/local --without-ldap --without-berkeley-db \
	    --without-pgsql --without-mysql --without-sqlite3 --without-iconv \
	    --with-apr=/usr/local --disable-shared
    sed -i -e 's/^AWK=mawk/AWK=awk/' -e "s/\<-g -O2\>/$CFLAGS/" build/rules.mk
    make
    sudo make install
    cd ..
    rm -rf apr-util-1.3.12
}

while read FN; do
    eval "[ -e $FN ] || rebuild"
done < MANIFEST
