#!/usr/bin/env bash

##    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 3 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.
##

# ===============
# check_postfixprocessed - plugin to check the number of mail processed by parsing logfiles
# ===============
# * mail processor written by Cecil Westerhof & Modifications for nagios by Frank IJskes
# * Christian Nutz identified the IF as slow on large logfiles, by only checking from the bottom up performance went back to normal

# version 2 uses AWK to improve processing / lower cpu load
# plugin return codes:
# 0     OK
# 1     Warning
# 2     Critical
# 3     Unknown

NO_OF_SECONDS=300
POSTFIX_LOG="/var/log/mail.log"

while getopts "hvw:c:" opt
do
        case $opt in
                h)
                        showhelp=1
                        break
                ;;
                w)
                        warning="$OPTARG"
                ;;
                c)
                        critical="$OPTARG"
                ;;
                v)
                        verbose=1
                ;;
        esac
done

printUsage() {
        echo "Usage: $0 [-h] [-v] -w <warning> -c <critical>"
        echo ""
        echo "Example: $0 -w 50 -c 100"
}

printHelp() {
        printUsage
        echo ""
        echo "This plugin checks the number of messages processed by Postfix in the last 5 minutes."
        echo ""
        echo "For more details, see inside the script ;)"
        echo ""
        exit 3
}

if [ "$showhelp" = "1" ]; then
        printHelp
        exit 3
fi

if [ ! "$warning" ] || [ ! "$critical" ]; then
        printUsage
        exit 3
fi

if [ $warning -ge $critical ]; then
        echo "<warning> has to be smaller than <critical>!"
        exit 3
fi

if [ ! "$POSTFIX_LOG" ]; then
        echo "Could not find postfix log!"
        exit 3
fi

countSentMessages () {
        NOW=`date +%s`

        DATE_FROM=`awk -v now=$NOW -v seconds=$NO_OF_SECONDS 'BEGIN{print strftime("%b %d %T", now-seconds)}'`
        DATE_TO=`awk -v now=$NOW 'BEGIN{print strftime("%b %d %T", now)}'`

        echo `awk '$0>=from && $0<=to' from="$DATE_FROM" to="$DATE_TO" ${POSTFIX_LOG} | grep ' postfix/smtp\[.*, status=sent ' | wc -l`
}

sentMessagesCount=`countSentMessages`

echo "Messages processed in the last $NO_OF_SECONDS seconds: $sentMessagesCount | mailsprocessed=$sentMessagesCount"

if [ "$sentMessagesCount" -ge "$critical" ]; then
        exit 2
elif [ "$sentMessagesCount" -ge "$warning" ]; then
        exit 1
else
        exit 0
fi