#! /bin/sh
#
# ZMailer startup and maintenance commands
#
#       Copyright 1990 by Rayan S. Zachariassen, all rights reserved.
#       This will be free software, but only when it is finished.
#
#       Some hacking by Matti Aarnio, Copyright 1990-2003
#       Modified for Debian by Christoph Lameter 1997
#

# -------- function definitions first, then main program below ---------

# -----------------------------------------------------------------------

checkfreeze () {
    if [ -f $POSTOFFICE/.freeze ]; then
	echo "Sorry, ZMailer is frozen, won't start anything until thawed !"
	echo "* CHECK THAT THE FREEZE CONDITION ISN'T DUE TO E.G. MAINTENANCE *"
	exit 2
    fi
}

# -----------------------------------------------------------------------

echoo () {
    [ "$quiet" = 0 ] && echo $eopt "$@$eeol"
}

# -----------------------------------------------------------------------

PATH=/bin:/usr/bin:/sbin:/usr/sbin
if [ -d /usr/ucb ]; then
    PATH=$PATH:/usr/ucb
fi
FLAGS="defaults 50"

unset ZCONFIG

if [ "$1" = "--zconfig" ] ; then
    shift
    ZCONFIG="$1"
    shift
    # If not readable, do not accept this setting
    if [ ! -r "$ZCONFIG" ] ; then
	unset ZCONFIG
    else
	setZCONFIG="-Z $ZCONFIG"
    fi
fi

# If  ZCONFIG  environment variable is not set now, give it hardcoded value
if [ "$ZCONFIG" = "" ] ; then
    ZCONFIG=/usr/local/etc/zmailer/zmailer.conf
fi
export ZCONFIG

# Make sure that if the system supports locales, that it treats time
# in one particular way. Lots of things expect it!
# Apparently some systems are prone to make wrong things with this
# environement variable set, but those are likely old and obsolete
# ones...  (Those systems have broken locale handling to begin with.)
LC_TIME=C
export LC_TIME


# Sense how the  echo  works, it is either, or..
# There are POSIX echos, SysV echos, BSD echos...
case "`echo 'foo\c'`" in
    foo)   eopt='' ; eeol='\c' ;;
    *)     eopt='-n' ; eeol='' ;;
esac

. $ZCONFIG || exit 1

#
# We NEED $MAILBIN directory as our first element
# in the $PATH variable; 
#
PATH=$MAILBIN:$PATH

case $POSTOFFICE in
    /*) ;;
    *)  echo "$0: panic!! can't initialize from $ZCONFIG"
            exit 1
            ;;
esac

cd $POSTOFFICE  # So that possible cores are there..

case "$MAILBOX" in
*%*)
    ;; # Format-rule, don't check it being a dir...
*)
    if [ ! -d $MAILBOX ]; then
        echo "$0: panic!!  MAILBOX-variable does not point to a directory!  Verify $ZCONFIG!"
        exit 1
    fi
    ;;
esac

quiet=0
if [ "$1" = "-q" ]; then
    shift
    quiet=1
fi

# set up the default arguments
if [ "$1" = "start" -o "$1" = "reload" -o $# = 0 ]; then
        set -$- router scheduler smtpserver
        echoo "Starting ZMailer mail server: "
fi

umask 022

KILL=

for op in $@
do
    shift

    case "$op" in

        stop|kill|nuke|kills|killr)     # print nothing
            ;;
        *)
            echoo "${op} "
            ;;
    esac
    case "$op" in
        router|outer)
            case $KILL in
                -*)
                    if [ -f $POSTOFFICE/.pid.router ]; then
                        router $setZCONFIG -k > /dev/null
        #           else
        #               echoo "(warning: no .pid.router file) "
                    fi
                    ;;
                *)
		    checkfreeze
                    router $setZCONFIG $ROUTEROPTIONS
                    ;;
            esac
            ;;
        sched*|ched*)
            case $KILL in
                -*)     kill $KILL -`cat $POSTOFFICE/.pid.scheduler` 2>/dev/null ;;
                *)
			checkfreeze
                        cd $POSTOFFICE/transport
                        # must send signal to scheduler to make it
                        # stop reading the directory for new files
                        PIDFILE=.pid.scheduler
                        if [ -f ../$PIDFILE ]; then
                            PID=`cat ../$PIDFILE`
                            kill -TERM -$PID 2>/dev/null
        #               else
        #                   echoo "(warning: no $PIDFILE file) "
                        fi
                        scheduler $setZCONFIG $SCHEDULEROPTIONS
                        ;;
            esac
            ;;
        smtp*|mtp*)
            case $KILL in
                -*)     if [ -f $POSTOFFICE/.pid.smtpserver ]; then
                            kill $KILL `cat $POSTOFFICE/.pid.smtpserver` 2>/dev/null
                        elif [ -d $POSTOFFICE/.pid.smtpserver ]; then
                            kill $KILL `cat $POSTOFFICE/.pid.smtpserver/* 2>/dev/null` 2>/dev/null
        #               else
        #                   echo "(warning: no .pid.smtpserver file) "
                        fi
                        ;;
                *)
			checkfreeze
                        cd $POSTOFFICE
                        if [ -f $MAILSHARE/smtpserver.conf ]; then
                            smtpserver $setZCONFIG $SMTPOPTIONS
                        elif [ -d $MAILSHARE/smtpserver.conf ]; then
                            if [ -e $POSTOFFICE/.pid.smtpserver ]; then
                                if [ ! -d $POSTOFFICE/.pid.smtpserver ]; then
                                    echo "CONFIGURATION ERROR!"
                                    echo "Cannot start multiple instances of the smtpserver -"
                                    echo "$POSTOFFICE/.pid.smtpserver is not a directory!"
                                    exit 0
                                fi
                            else
                                mkdir $POSTOFFICE/.pid.smtpserver
                            fi
                            cd $MAILSHARE/smtpserver.conf
                            for serv in *; do
                                SMTPOPTIONS_SAVE=$SMTPOPTIONS
                                if [ -f .$serv ]; then
                                    SMTPOPTIONS=`eval echo \`cat .$serv\``
                                fi
                                smtpserver $setZCONFIG $SMTPOPTIONS -C $serv -I .pid.smtpserver/$serv
                                SMTPOPTIONS=$SMTPOPTIONS_SAVE
                            done
                        fi
                        ;;
            esac
            ;;
        newdb)
            #
            #  Translate all common flatfile databases to binary db's
            #
	    if [ -r $MAILVAR/db/dbases.conf ]; then
		newdbprocessor $MAILVAR/db/dbases.conf
	    else
		echoo "( "
                if [   -f $MAILVAR/db/routes -a  \
                     ! -f $MAILVAR/db/routes.zmsh ] ; then
                    echoo "routes "
                    newdb -l $MAILVAR/db/routes
                fi
                if [   -f $MAILSHARE/db/mboxmap -a  \
                     ! -f $MAILSHARE/db/mboxmap.zmsh ] ; then
                    echoo "mboxmap "
                    newdb -l $MAILSHARE/db/mboxmap
                fi
                if [   -f $MAILVAR/db/localnames -a \
                     ! -f $MAILVAR/db/localnames.zmsh ] ; then
                    echoo "localnames "
                    newdb -l $MAILVAR/db/localnames
                fi
                if [ -f $MAILVAR/db/aliases ] ; then
                    echoo "aliases "
                    newaliases -s
                fi
                if [ -f $MAILVAR/db/fqdnaliases ] ; then
                    echoo "fqdnaliases "
                    newfqdnaliases -s
                fi
                echoo ") "
	    fi
            ;;
        newf*)
            newfqdnaliases
            ;;
        newal*)
            newaliases
            ;;
        new-route*)
            newdb -l $MAILVAR/db/routes
            ;;
        new-local*)
            newdb -l $MAILVAR/db/localnames
            ;;
        logsync)
            # Over the years less and less of ZMailer subsystems
            # need poking for logfile restarts.  Initially about
            # all needed them, then smtpserver changed to have the
            # log opened separately for each session, and now [Dec 1999]
            # the router has learned better ways.  [2003-Apr]
	    # Even scheduler does not need explicite knocking.
	    # (
            ;;
        logrotate)
            rotate-logs.sh
            ;;
	star*)
	    KILL=""
	    
	    ;;
        stop|kill|nuke|kills|killr)
            case $# in
                0)      exec zmailer --zconfig $ZCONFIG $op router scheduler smtpserver ;;
            esac
            case $op in
                kill|stop|kills|killr)
                    KILL="-TERM"
                    echoo "Stopping ZMailer services: "
                    ;;
                nuke)
                    KILL="-KILL"
                    echoo "Aborting ZMailer services: "
                    ;;
            esac
            ;;

        resubmit)
            (cd $POSTOFFICE/deferred &&				\
		find . -type f -print |				\
		/usr/bin/perl -ne 'chomp; $new = $_; $new =~ s#^.*/##;	\
			    rename($_, "../router/" . $new) or	\
	printf STDERR "rename %s -> ../router/%s failed; %s\n", $_, $new, $!;' )
            ;;

        bootclean)
            rm -f $POSTOFFICE/.pid.* 2> /dev/null
            ;;

        cleanup)
            (cd $POSTOFFICE ;
             find public -type f -mtime +2 -print | xargs rm -f
             find postman -type f -mtime +7 -name '[0-9]*' -print | xargs rm -f
            )
            ;;
        freeze)
            touch $POSTOFFICE/.freeze
            ;;
        unfr*|thaw)
            rm -f $POSTOFFICE/.freeze
            ;;
	-q)
	    ;;
        *)
            echo "$0: unknown option: $op"
            errflg=1
            ;;
    esac
done

[ "$quiet" = 0 ] && echo

case $errflg in
    1)  echo Usage: $0 "[--zconfig /file/path] [ start | router | scheduler | smtpserver | stop | kill | resubmit | bootclean | cleanup | newdb | logrotate | logsync | freeze | thaw ]"
        exit 1
        ;;
esac
exit 0
