#!/bin/sh
# ------------------------------------------------------------------------------
# check_spamassassin_effectiveness.sh - compares recognized spam with learned spam
# Copyright (C) 2006  NETWAYS GmbH, www.netways.de
# Author: Gerd Mueller <gmueller@netways.de>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# ------------------------------------------------------------------------------

WARN=$2
CRIT=$1


BC_SCALE_MAX=4

TODAY=`date "+%b %e" -d -1day`
YESTERDAY=`date "+%b %e" -d -2day`

TOTAL_1=`cat /var/log/amavis.log  | grep "$YESTERDAY" | grep "Passed\|Infected" -c `
TOTAL_2=`zcat /var/log/amavis.log.1.gz /var/log/amavis.log.2 | grep "$YESTERDAY" | grep "Passed\|Infected" -c `
SPAM_1=`cat /var/log/amavis.log  | grep "$YESTERDAY" | grep "Passed" | grep "quarantine" -c `
SPAM_2=`zcat /var/log/amavis.log.1.gz /var/log/amavis.log.2.gz | grep "$YESTERDAY" | grep "Passed" | grep "quarantine" -c `
LEARNED_1=`cat /var/log/syslog | grep "$TODAY" | grep fetchmail | grep "messages for spamassassin" | awk 'BEGIN {SUM=0} {SUM=SUM+$6} END {print SUM}'`
LEARNED_2=`zcat /var/log/syslog.1.gz /var/log/syslog.2.gz | grep "$TODAY" | grep fetchmail | grep "messages for spamassassin" | awk 'BEGIN {SUM=0} {SUM=SUM+$6} END {print SUM}'`

LEARNED="0"`echo "$LEARNED_1+$LEARNED_2"| bc`
TOTAL="0"`echo "$TOTAL_1+$TOTAL_2"| bc`
SPAM="0"`echo "$SPAM_1+$SPAM_2"| bc`

TOTAL_SPAM=`echo "$SPAM+$LEARNED" | bc `

RC=0
RC_TEXT="OK"

if [ "$TOTAL_SPAM" = "" -o "$TOTAL_SPAM" = "0" ] 
then
  TOTAL_SPAM="0";
  TOTAL_SPAM_PERC="100";
else
  TOTAL_SPAM_PERC=`echo "$SPAM*100/$TOTAL_SPAM" | bc `
fi

if [ "$WARN" == "" ]
then
  WARN=$TOTAL_SPAM_PERC
fi

if [ "$CRIT" == "" ]
then
  CRIT=$TOTAL_SPAM_PERC
fi

if [ $TOTAL_SPAM_PERC -lt $CRIT ]
then
	RC=2
	RC_TEXT="CRITICAL"
else if [ $TOTAL_SPAM_PERC -lt $WARN ]
then
	RC=1
	RC_TEXT="WARNING"
fi fi

echo "$RC_TEXT: recognized $SPAM of $TOTAL_SPAM spam mails ($TOTAL_SPAM_PERC%)| total=$TOTAL spam=$SPAM learn=$LEARNED percent=$TOTAL_SPAM_PERC "
exit $RC
