#! /bin/bash
#
# postfix:       start/stop/reload/restart the postfix deamon
#
# chkconfig:     2345 98 2
#
# description:   What is Postfix?
#                It is Wietse Venema's mailer that started life as an alternative to the widely-used Sendmail program
#                Postfix is a Mail Transport Agent (MTA), supporting LDAP, SMTP AUTH (SASL), TLS and running in a chroot environment.
#

. /etc/init.d/functions
IMSS_HOME=_PKG_INSTALL_ROOT_
export PATH=$IMSS_HOME/postfix/usr/sbin/:$IMSS_HOME/postfix/usr/bin/:$IMSS_HOME/postfix/usr/libexec/postfix:/sbin:/usr/sbin:/bin:/usr/bin:$PATH
export LD_LIBRARY_PATH=$IMSS_HOME/lib/curl:${IMSS_HOME}/lib

LOGGER="/usr/bin/logger"
POSTFIX="${IMSS_HOME}/postfix/usr/sbin/postfix"

rc=0
if [ -f /etc/trend-release ]; then
	trap "" SIGINT
	trap "unlock" EXIT
	
	. /etc/lock_functions
	
	lock
else
    if [ "$1" == "flush" ]; then
        echo "postfix flush"
        postfix $1
        exit $?
    fi
    exit 0
fi

if [ ! -f $POSTFIX ] ; then
    $LOGGER -t $0 -s -p mail.err "Unable to locate Postfix"
    exit 1
fi

if [ ! -f ${IMSS_HOME}/postfix/etc/postfix/main.cf ] ; then
    if [ -f ${IMSS_HOME}/postfix/etc/postfix/main.cf.bak ] ; then
        $LOGGER -t $0 -s -p mail.err "Restore Postfix configuration from main.cf.bak"
        cp ${IMSS_HOME}/postfix/etc/postfix/main.cf.bak ${IMSS_HOME}/postfix/etc/postfix/main.cf
    else
        $LOGGER -t $0 -s -p mail.err "Unable to locate Postfix configuration"
        exit 1
    fi
fi

case "$1" in
    start)
        ps -ef | grep "${IMSS_HOME}/postfix/usr/libexec/postfix/master" | grep -v grep >/dev/null 2>&1
        if [ $? = 0 ]; then
        	echo "the Postfix mail system is already running"
        fi
        echo -n "Starting Postfix"
        $POSTFIX start 2> >(grep -v "libTmFoxSocketLib.so")
        rc=$?
        if [ $rc = 0 ]; then
        	echo_success
       	else
       		echo_failure
        fi
        echo
        ;;

    stop)
        ps -ef | grep "${IMSS_HOME}/postfix/usr/libexec/postfix/master" | grep -v grep >/dev/null 2>&1
        if [ $? -ne 0 ]; then
        	echo "the Postfix mail system is not running"
        fi
        echo -n "Stopping Postfix"
        $POSTFIX stop 2> >(grep -v "libTmFoxSocketLib.so")
        rc=$?
		rm -rf /var/spool/postfix/pid/master.pid
		if [ $rc = 0 ]; then
			echo_success
       	else
       		echo_failure
		fi
		echo
        ;;
        
    # flush)
        # ps -ef | grep "${IMSS_HOME}/postfix/usr/libexec/postfix/master" | grep -v grep >/dev/null 2>&1
        # if [ $? -ne 0 ]; then
                # echo "the Postfix mail system is not running"
        # fi
        # echo "Flushing Postfix"
        # $POSTFIX flush 2> >(grep -v "libTmFoxSocketLib.so")
        # rc=$?
        # if [ $rc = 0 ]; then
                # echo_success
        # else
                # echo_failure
        # fi
        # echo
        # ;;

    flush)
        # check if postfix is running
        ps -ef | grep "${IMSS_HOME}/postfix/usr/libexec/postfix/master" | grep -v grep >/dev/null 2>&1
        if [ $? -ne 0 ]; then
                echo "the Postfix mail system is not running"
                
                # We should either start Postfix or exit here
                postlog "FLUSH: Postfix not running. Trying to start the service."
                echo -n "Starting Postfix"
                $POSTFIX start 2> >(grep -v "libTmFoxSocketLib.so")
                rc=$?
                if [ $rc = 0 ]; then
                    echo_success
                    echo
                else
                    echo_failure
                    echo
                    exit
                fi
        fi
        
        # Use netcat to try connecting to lo:10025 to see if IMSS is ready accepting new connections
        echo "Waiting for IMSS to initialise"
        postlog "FLUSH: Checking if IMSS is running."
        TRY=0
        while [ `echo "QUIT" |nc -w 1 localhost 10025 |egrep "^221 " |wc -l` -ne 1 ]
        do
                postlog "FLUSH: IMSS not running. Sleeping 5 seconds."
                sleep 5
                TRY=$(( $TRY + 1 ))
                if [ $TRY -gt 12 ]      # Wait up to one minute
                then
                        postlog "FLUSH: IMSS still not runnnig. Giving up."
                        echo "IMSS is still down, exiting"
                        echo_failure
                        echo
                        exit
                fi
        done
        
        # Flush all queued emails that were received in the last N minutes
        # N = last service shutdown time OR 5 minutes.
        echo "Flushing Postfix"
        postlog "FLUSH: Starting to flush \"new\" queue objects."
        FILE=`ls -ltr ${IMSS_HOME}/log/log.imss* |tail -1 |awk '{print $9}'`
        DATE=`grep "mainloop interrupt signal is received. Signal all child processes to exit.." $FILE |tail -1`
        if [ "$DATE" != "" ]
        then
                DATE=`echo $DATE |awk '{print $1" "$2}'`
                TSTAMP=`date --date="$DATE" +%s`
                DDIFF=$(( `date +%s` - $TSTAMP ))
                DIFMIN=$(( $DDIFF / 60 ))
                find /var/spool/postfix/deferred -type f -cmin -$(( $DIFMIN + 2 )) |perl -ne 'qx{postqueue -i $_} for m{/(\w{10,11})$};'
#               find /var/spool/postfix/deferred -type f -cmin -$(( $DIFMIN + 2 )) |egrep -o "[0-9A-F]{10,11}" | postsuper -R -
#               echo "W" > /var/spool/postfix/public/pickup
        else
                find /var/spool/postfix/deferred -type f -cmin -5 |perl -ne 'qx{postqueue -i $_} for m{/(\w{10,11})$};'
#               find /var/spool/postfix/deferred -type f -cmin -5 |egrep -o "[0-9A-F]{10,11}" | postsuper -R -
#               echo "W" > /var/spool/postfix/public/pickup
        fi
        echo_success
        postlog "FLUSH: SUCCESS... And we're out :)"
        echo
        ;;

    reload)
        ps -ef | grep "${IMSS_HOME}/postfix/usr/libexec/postfix/master" | grep -v grep >/dev/null 2>&1
        if [ $? -ne 0 ]; then
        	echo "the Postfix mail system is not running"
        fi
        echo "Reloading Postfix"
        $POSTFIX reload 2> >(grep -v "libTmFoxSocketLib.so")
        rc=$?
        if [ $rc = 0 ]; then
        	echo_success
       	else
       		echo_failure
        fi
        echo
        ;;

	restart)
        echo "Restarting Postfix"
        ps -ef | grep "${IMSS_HOME}/postfix/usr/libexec/postfix/master" | grep -v grep >/dev/null 2>&1
        if [ $? -ne 0 ]; then
                echo "the Postfix mail system is not running"
        fi
        $POSTFIX stop 2> >(grep -v "libTmFoxSocketLib.so")
        rc=$?
        echo -n "Stopping Postfix"
        if [ $rc = 0 ]; then
                echo_success
        else
                echo_failure
        fi
        echo
        $POSTFIX start 2> >(grep -v "libTmFoxSocketLib.so")
        rc=$?
        echo -n "Starting Postfix"
        if [ $rc = 0 ]; then
                echo_success
        else
                echo_failure
        fi
        echo
        ;;

	status)
		status -p /var/spool/postfix/pid/master.pid master
		rc=$?
		;;

    *)
        echo "Usage: $0 {start|stop|reload|restart|flush}"
        rc=1

esac
exit $rc
