#!/bin/bash
#
# Plugin to monitor incoming DKIM mail.
#
# Florian Sager, sager@agitos.de, 2008-02-06
#
# Parameters understood:
#
#       config   (required)
#       autoconf (optional)
#
# Gives the result of the verification. The following values are possible:
# 
# pass
#     Returned if a valid DKIM-Signature header was found, and the signature contains a correct value for the message.
#
# fail
#     Returned if a valid DKIM-Signature header was found, but the signature does not contain a correct value for the message.
#
# invalid
#     Returned if no valid DKIM-Signature headers were found, but there is at least one invalid DKIM-Signature header. For a reason why a DKIM-Signature header found in the message was invalid, see $dkim->{signature_reject_reason}.
#
# none
#     Returned if no DKIM-Signature headers (valid or invalid) were found.
# 
# In case of multiple signatures, the "best" result will be returned. Best is defined as "pass", followed by "fail", "invalid", and "none".
# 

mktempfile () {
mktemp -t
}

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

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 DKIM Proxy mails'
        echo 'graph_order dkimnone dkimpass dkiminvalid dkimfail'
        echo 'graph_category mail'
        echo 'graph_vlabel Count'
        echo 'graph_args --base 1000 -l 0'
#       echo 'graph_total total'

        echo 'dkimnone.label No DKIM-Sigs'
        echo 'dkimnone.min 0'
        echo 'dkimpass.label Valid DKIM-Sigs'
        echo 'dkimpass.min 0'
        echo 'dkiminvalid.label Invalid DKIM-Sigs'
        echo 'dkiminvalid.min 0'
        echo 'dkimfail.label Failed DKIM-Sigs'
        echo 'dkimfail.min 0'        
        exit 0
fi

dkimnone=U
dkimpass=U
dkiminvalid=U
dkiminfail=U

TEMP_FILE=`mktempfile munin-dkimproxy_mails.XXXXXX`

if [ -n "$TEMP_FILE" -a -f "$TEMP_FILE" ]
then
        $LOGTAIL ${MAIL_LOG} $STATEFILE | grep "DKIM verify - " > ${TEMP_FILE}

        dkimnone=`grep 'DKIM verify - none' ${TEMP_FILE} | wc -l`
        dkimpass=`grep 'DKIM verify - pass' ${TEMP_FILE} | wc -l`
        dkiminvalid=`grep 'DKIM verify - invalid' ${TEMP_FILE} | wc -l`
        dkimfail=`grep 'DKIM verify - fail' ${TEMP_FILE} | wc -l`

        /bin/rm -f $TEMP_FILE
fi

echo "dkimnone.value ${dkimnone}"
echo "dkimpass.value ${dkimpass}"
echo "dkiminvalid.value ${dkiminvalid}"
echo "dkimfail.value ${dkimfail}"
