#! @MAILBIN@/router -f
#
# This zshell script recreates the FQDN alias map
#
# 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=@ZMAILERCFGFILE@

. $ZCONFIG

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

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

trap "rm -rf $ALIASFILE.$$" 0

if mkdir $ALIASFILE.$$ ; then
	;
else
	echo 'Please check and remove the "'$ALIASFILE.$$'" (scratch) directory'
	exit 1
fi

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

printaliases -v -o $ALIASFILE.$$/idx $ALIASES > $ALIASFILE.$$/dat
case $? in
0)	;;
*)	x=$? ; echo '"'$ALIASFILE'" rebuilding aborted' ; exit $x
	;;
esac

# See comment below (*)

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

sort $ALIASFILE.$$/idx -o $ALIASFILE.$$/idx

mv $ALIASFILE.dat $ALIASFILE.$$/odat
mv $ALIASFILE.idx $ALIASFILE.$$/oidx

mv $ALIASFILE.$$/dat $ALIASFILE.dat && mv $ALIASFILE.$$/idx $ALIASFILE.idx

# 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
