#! /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 LVM2.2.02.98.tgz
    cd LVM2.2.02.98
    ./configure --disable-readline --enable-realtime --disable-selinux \
	    --disable-nls --disable-fsadm --disable-dmeventd --with-lvm1=none \
	    --with-pool=none --with-mirrors=internal --with-cluster=none \
	    --with-clvmd=none --with-raid=none --with-optimisation=''
    make
    strip -R .note -R .comment libdm/libdevmapper.so.1.02 tools/lvm
    mkdir -p ../libdevmapper102/lib
    cp libdm/libdevmapper.so.1.02 ../libdevmapper102/lib/
    cp tools/lvm ../lvm2/sbin/
    cd ..
    rm -rf LVM2.2.02.98
}

mkdir -p lvm2/sbin
for LINK in lvchange lvconvert lvcreate lvdisplay lvextend lvmchange \
	lvmdiskscan lvmsadc lvmsar lvreduce lvremove lvrename lvresize lvs \
	lvscan pvchange pvck pvcreate pvdisplay pvmove pvremove pvresize pvs \
	pvscan vgcfgbackup vgcfgrestore vgchange vgck vgconvert vgcreate \
	vgdisplay vgexport vgextend vgimport vgmerge vgmknodes vgreduce \
	vgremove vgrename vgs vgscan vgsplit; do
    ln -sf lvm lvm2/sbin/$LINK
done

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
