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

set -e
shopt -s extglob

mailuser=${mailuser-daemon}
mailgroup=${mailgroup-daemon}

getent group ${mailgroup} >/dev/null || groupadd -r ${mailgroup}
getent passwd ${mailuser} >/dev/null || useradd -r -g ${mailgroup} -d /usr/local/lib/courier -s /bin/nologin -c "Courier Mail Server" ${mailuser}

f=`cd .. && ls courier-authlib-0.72.4.tar* | sed -n 1p`

rm -rf deb
mkdir deb
cp ../$f deb/`echo $f | sed 's/courier-authlib-/courier-authlib_/;s/.tar./.orig.tar./'`
cd deb
tar xf *
cd courier-authlib-0.72.4
cp -pr packaging/debian .

if test "$DEBGCC" = ""
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
    DEBGCC=""
else
    DEBGCC="-$DEBGCC"
fi

for f in debian/rules debian/control debian/auto_install.sh.in
do
	sed "
s/%SOVERSION%/0/g
s/%MAILUSER%/$mailuser/g
s/%MAILGROUP%/$mailgroup/g
s~%DEBGCC%~$DEBGCC~g
" <packaging/$f >$f.tmp
mv $f.tmp $f
done

chmod +x debian/rules

debuild "$@"
cd ..
rm -rf courier-authlib-0.72.4
echo "Built packages in the deb subdirectory."
