#!/bin/sh
MONITOR=/var/log/owmtail.log
MAILFROM="openwebmail monitor"
MAILTO=email@servizio.calcolo
MSGFILE=/root/utils/owm.message
MAXREC=47

start=$(date -d "`head -1 $MONITOR|awk '{print $2,$3,$4}'`" +%s)
now=`date +%s`
secs=`expr $now - $start`
/bin/echo -e "Subject: Allarme SPAM da openwebmail\n\nElenco utenti che hanno spedito a piu\` di $MAXREC destinatari in $secs secondi\n" > $MSGFILE
cat $MONITOR | awk '{if ($11=="send" && $12=="message" && substr($14,1,8)=="subject=") {i=14; while ($i != "-") {i=i+1}; tail=""; while (i <= NF) {tail=tail" "$i;i=i+1}; print $9" , "tail}}' | awk -F, '{i=2; r=0; while (i <= NF) {if (index($i,"@")>0){r=r+1} ; i=i+1} ; print $1,r}' | sort | awk '{if ($1==prec) {mail=mail+1;addr=addr+$2} else {if (NR!=1) {printf "%-9s %5d %9d\n",prec,mail,addr} ; prec=$1; mail=1; addr=$2 }} END {printf "%-9s %5d %9d\n",prec,mail,addr}'|sort -k3 -rn|awk -v maxrec=$MAXREC 'BEGIN {print "Username    mail  recipients"}{if ($3>maxrec) print $0}' >> $MSGFILE
/bin/echo -e "\n\nControllare /var/log/openwebmail.log su `hostname -s`" >> $MSGFILE
date > $MONITOR
if [ `wc -l $MSGFILE | awk '{print $1}'` -gt 8 ] ; then
   cat $MSGFILE | /usr/sbin/sendmail -F "$MAILFROM" $MAILTO
fi
