#! /bin/bash
#
# Wrapper script for running debuild to build this package.
#
# export DEBGCC=12
#
# Set DEBGCC to use a non-default version of gcc
#
# export DEBCLANG=20
#
# Set DEBCLANG to use clang instead of gcc

set -e
shopt -s extglob

eval `courierauthconfig --configfiles`
f=`cd .. && ls maildrop-4.0.3.tar* | sed -n 1p`

rm -rf deb
mkdir deb
cp ../$f deb/`echo $f | sed 's/maildrop-/maildrop_/;s/.tar./.orig.tar./'`
cd deb
tar xf *
cd maildrop-4.0.3
cp -pr packaging/debian .

if test "$DEBGCC" = "" -a "$DEBCLANG" = ""
then
    DEBGCC=`readlink /usr/bin/gcc | sed 's/gcc-//'`

    case "$DEBGCC" in
	[1-9]*([0-9]))
		      ;;
	*)
	    echo "Cannot determine gcc version"
	    exit 1
	    ;;
    esac
fi

if test "$DEBGCC" = "default"
then
    CCOMPILER="gcc"
    CXXCOMPILER="g++"
else
    if test "$DEBCLANG" = ""
    then
	CCOMPILER="gcc-$DEBGCC"
	CXXCOMPILER="g++-$DEBGCC"
    else
	CCOMPILER="clang-$DEBCLANG"
	CXXCOMPILER="clang++-$DEBCLANG"
    fi
fi

case $CCOMPILER in
    clang*)
	BUILD_DEPENDS="$CCOMPILER"
	;;
    *)
	BUILD_DEPENDS="$CCOMPILER, $CXXCOMPILER"
	;;
esac

for f in debian/rules debian/control
do
	sed "
s/%SOVERSION%/0/g
s/%CCOMPILER%/$CCOMPILER/g
s/%CXXCOMPILER%/$CXXCOMPILER/g
s/%BUILD_DEPENDS%/$BUILD_DEPENDS/g
s/%MAILUSER%/$mailuser/g
s/%MAILGROUP%/$mailgroup/g
" <packaging/$f >$f.tmp
mv $f.tmp $f
done

chmod +x debian/rules

debuild "$@"
cd ..
rm -rf maildrop-4.0.3
echo "Built packages in the deb subdirectory."
