#! /bin/sh
#
ROOT=/netlog
source $ROOT/etc/netlog.conf
LOGPID=$ROOT/var/run/mailout.pid
DUMP=$LOGDIR/mailout.dump
MAXOUT=50          # Numero max mail/min
MAILALERT=email@servizio.calcolo

if [ -e $DUMP ] ; then
   mv -f $DUMP $LOGDIR/mailout.dump.1
fi

if [ -f $LOGPID ] ; then
   STARTSEC=`stat -t $LOGPID| awk '{print $13}'`
   STOPSEC=`date +%s`
   OLDPID=`head -1 $LOGPID`
   if [ "$OLDPID" ] ; then
      if [ -e "/proc/$OLDPID" ] ; then
         echo "`date`: sending TERM signal to process $OLDPID" >> $LOGDIR/mailoutdump.err
         kill -TERM $OLDPID
         if [ $? = 1 ] ; then
            echo "`date`: error sending TERM signal to process $OLDPID" 1>&2 >> $LOGDIR/mailoutdump.err
         fi 
         sleep 3
         if [ -e /proc/$OLDPID ] ; then
            echo "`date`: process $OLDPID not terminated" 1>&2 >> $LOGDIR/mailoutdump.err
            echo "`date`: process $OLDPID not terminated" | mail -s "mailoutdump error" $MAILREPORT
         else
            echo "`date`: process $OLDPID terminated" 1>&2 >> $LOGDIR/mailoutdump.err
         fi
      fi
   fi
fi


echo "`date`: >>>>>>>>> newdump <<<<<<<<<<" 1>&2 >> $LOGDIR/mailoutdump.err
echo "`date`: starting new mailoutdump process..." 1>&2 >> $LOGDIR/mailoutdump.err
set -m
$LOGPROG -i $DEVICE -nlF $FILTERDIR/mailout 2>>$LOGDIR/mailoutdump.err > $DUMP &
NEWPID="`jobs -l | awk '{if (NR==1) print $2}'`"
echo "`date`: process $NEWPID started" 1>&2 >> $LOGDIR/mailoutdump.err
echo "$NEWPID" > $LOGPID
checkpids=`ps axw | grep "$LOGPROG -i $DEVICE -nlF $FILTERDIR/mailout" | grep -v grep | awk '{print $1}'`
if [ `echo $checkpids | wc -w` -gt 1 ] ; then
   echo "`date`: more than one dump running. PIDS are $checkpids" | mail -s "mailoutdump error" $MAILREPORT
fi

if [ -e $LOGDIR/mailout.dump.1 ] ; then
   NOUT=`wc -l $LOGDIR/mailout.dump.1|awk '{print $1}'`
   if [ $NOUT -gt 0 -a $STOPSEC -gt $STARTSEC ] ; then
      FOUT=`expr $NOUT '*' 60 / \( $STOPSEC - $STARTSEC \)`
      if [ $FOUT -gt $MAXOUT ] ; then
         echo -e "$NOUT mail spediti all'esterno negli ultimi `expr $STOPSEC - $STARTSEC` secondi (`expr $NOUT '*' 60 / \( $STOPSEC - $STARTSEC \)` mail/min)\nNormalmente la frequenza di invio e' inferiore a `expr $MAXOUT` mail/min\n\nControllare i log del mailserver che effettua l'invio per trovare la macchina da cui partono i messaggi.\n\nSegue l'elenco delle ultime `expr \( $STOPSEC - $STARTSEC \) '*' $MAXOUT / 60` aperture di connessione:\n\n    Time          server interno        server esterno\n`cat $LOGDIR/mailout.dump.1|tail -$( expr \( $STOPSEC - $STARTSEC \) '*' $MAXOUT / 60 ) | awk '{print $1,$2,$3,$4}'`" | mail -s "Allarme SPAM in uscita" $MAILALERT
      fi
   fi
fi
