#!/bin/sh
#
# Plugin to monitor the amavis mail filter.
#
# Usage: Place in /etc/lrrd/client.d/ (or link it there  using ln -s)
#
# Parameters understood:
#
# 	config   (required)
# 	autoconf (optional)
#
# Config variables:
#
#       amavislog    - file where amavis logs are written
#

TEMP_FILE=`mktemp /tmp/lrrd-amavis.XXXXXX`
AMAVIS_LOG=${logfile:-/var/log/mail/mail.info}
LOGTAIL=${logtail:-`which logtail`}
STATEFILE=/var/munin/plugin-state/amavis.offset

if [ "$amavislog"  ]; then AMAVIS_LOG=$amavislog ; fi

if [ "$1" = "autoconf" ]; then
        if [ -f "${AMAVIS_LOG}" -a -n "${LOGTAIL}" -a -x "${LOGTAIL}" ] ; then
		echo yes
		exit 0
	else
		echo no
		exit 1
	fi
fi

# Try tailing a random file to check how arguments are passed
ARGS=0
`$LOGTAIL /etc/hosts 2>/dev/null >/dev/null`
if [ $? = 66 ]; then
    if [ ! -n "$logtail" ]; then
	ARGS=1
    fi
fi

if [ "$1" = "config" ]; then
	echo 'graph_title Amavis filter statistics'
	echo 'graph_order virus spam_maybe spam_sure total'
	echo 'graph_vlabel nb'
	echo 'virus.label virus'
	echo 'spam_maybe.label probably spam'
	echo 'spam_sure.label surely spam'
	echo 'total.label total'
	exit 0
fi

total=U
virus=U
spamm=U
spams=U

if [ -e $TEMP_FILE -a -f $TEMP_FILE ]
then
	if [ $ARGS != 0 ]; then
	    $LOGTAIL -f ${AMAVIS_LOG} -o ${STATEFILE} | grep 'amavis\[.*\]:' > ${TEMP_FILE}
	else
	    $LOGTAIL ${AMAVIS_LOG} ${STATEFILE} | grep 'amavis\[.*\]:' > ${TEMP_FILE}
	fi
	total=`cat ${TEMP_FILE} | wc -l`
	virus=`grep INFECTED ${TEMP_FILE} | wc -l`
	spamm=`grep 'Passed.*Hits: 1[0-9][.]' ${TEMP_FILE} | wc -l`
	spams=`grep 'Passed.*Hits: [2-9][0-9][0-9]*[.]' ${TEMP_FILE} | wc -l`
	/bin/rm $TEMP_FILE
fi

echo "virus.value ${virus}"
echo "spam_maybe.value ${spamm}"
echo "spam_sure.value ${spams}"
echo "total.value ${total}"
