#!/bin/bash
#
# Plugin to monitor incoming Postgrey
#
# Parameters understood:
#
# 	config   (required)
# 	autoconf (optional)
#


mktempfile () {
mktemp -t 
}       

MAIL_LOG=${logfile:-/var/log/mail.log}
STATEFILE=/var/lib/munin/plugin-state/postgrey.offset
LOGTAIL=${logtail:-`which logtail`}

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

if [ "$1" = "config" ]; then
	echo 'graph_title Postgrey daily filtering'
	echo 'graph_order delayed passed whitelisted'
	echo 'graph_category mail'
	echo 'graph_vlabel Count'
	echo 'graph_scale no'

##	echo 'graph_args --base 1000 -l 0'
	echo 'delayed.label delayed'
#	echo 'delayed.type DERIVE'
	echo 'passed.label passed'
#	echo 'passed.type DERIVE'
	echo 'whitelisted.label whitelisted'
#	echo 'whitelisted.type DERIVE'

        exit 0
fi


delayed=0
passed=0
whitelisted=0

ARGS=0
`$LOGTAIL /etc/hosts 2>/dev/null >/dev/null`
if [ $? = 66 ]; then
    if [ ! -n "$logtail" ]; then
	ARGS=1
    fi
fi

TEMP_FILE=`mktempfile munin-postgrey.XXXXXX`

if [ -n "$TEMP_FILE" -a -f "$TEMP_FILE" ]
then
	if [ $ARGS != 0 ]; then
	    $LOGTAIL ${MAIL_LOG} $STATEFILE | grep 'post[fix|grey]' > ${TEMP_FILE}
	else
	    $LOGTAIL ${MAIL_LOG} $STATEFILE | grep 'post[fix|grey]' > ${TEMP_FILE}
	fi

	delayed=`grep 'Recipient address rejected.*Greylisted' ${TEMP_FILE} | wc -l`
	passed=`grep 'postgrey\[[0-9]*\]: delayed [0-9]* seconds:' ${TEMP_FILE} | wc -l` 
	whitelisted=`grep 'postgrey\[[0-9]*\]: whitelisted:' ${TEMP_FILE} | wc -l`

	/bin/rm -f $TEMP_FILE
fi

echo "delayed.value ${delayed}"
echo "passed.value ${passed}"
echo "whitelisted.value ${whitelisted}"

