#! /usr/lib/zmailer/router -f
#
# This zshell script recreates the traditional aliases file database.
#
# NB!  If your kernel supports #! but the mechanism fails mysteriously when
# invoking this file, remember the total length of the command's path is
# limited to 30 characters or so.
#
ZCONFIG=/etc/zmailer/zmailer.conf

. $ZCONFIG

PATH=/bin:/usr/bin:$PATH # ZMailer router paths are a bit restrictive..

ALIASFILE=${1:-$MAILVAR/db/aliases}

trap "rm -f $ALIASFILE.$$*" 0

#echo -n 'Do you really want to rebuild alias file "'$ALIASFILE'"? [n] '
#read answer
#case "$answer" in
#[yY]*)	;;
#*)	exit 1 ;;
#esac

if [ -f $ALIASFILE.private ]; then
	cat - $ALIASFILE $ALIASFILE.private > $ALIASFILE.all <<- EOF
		# Do not edit this file, instead edit $ALIASFILE
		# and $ALIASFILE.private.
		EOF
	ALIASES=$ALIASFILE.all
else
	ALIASES=$ALIASFILE
fi

#
# We are compiling ALIAS file, using '-a' to tell that we may
# have continuation lines lurking there...
#
$MAILBIN/makedb -a $DBTYPE $ALIASFILE.$$ < $ALIASES

case $? in
0)	;;
*)	x=$? ; echo '"'$ALIASFILE'" rebuilding aborted'
	rm -f $ALIASFILE.$$.*
	exit $x
	;;
esac

# See comment below (*)

#if [ -s $POSTOFFICE/.pid.router ]; then
#	kill -STOP $(cat $POSTOFFICE/.pid.router) 2>&1 > /dev/null
#fi

# Now install the files

case "$DBTYPE" in
btree)
	mv $ALIASFILE.$$.db $ALIASFILE.db
	;;
ndbm)
	mv $ALIASFILE.$$.dir $ALIASFILE.dir
	mv $ALIASFILE.$$.pag $ALIASFILE.pag
	;;
dbm)
	mv $ALIASFILE.$$.dir $ALIASFILE.dir
	mv $ALIASFILE.$$.pag $ALIASFILE.pag
	;;
gdbm)
	mv $ALIASFILE.$$.gdbm $ALIASFILE.gdbm
	;;
esac

# The 'trap' takes care of removing the old dat/idx files, which triggers
# the reopen of the alias database due to the '-m' flag on the alias relation.
# (*)If the '-m' flag is not used, something like this construct should be used:

#if [ -s $POSTOFFICE/.pid.router ]; then
#	kill -CONT $(cat $POSTOFFICE/.pid.router) 2>&1 > /dev/null
#	kill -16 $(cat $POSTOFFICE/.pid.router) ||
#		echo "The router isn't running, remember to restart it!"
#fi
