#!/usr/local/bin/bash
#
# check_mailstats - Nagios sendmail mailstats parsing script
# version 1.0   18.11.2012
# by Mikanoshi - iam@mikanoshi.name, http://en.mikanoshi.name
# tested on FreeBDS 8.3
#
# IMPORTANT!
# /var/log/sendmail.st must have 644 permissions
# Also disable its rotation if it's active in newsyslog.conf (file doesn't grow in size)
#
# This Nagios plugin is free software, and comes with ABSOLUTELY NO WARRANTY.
# It may be used, redistributed and/or modified under the terms of the
# GNU General Public Licence (see http://www.fsf.org/licensing/licenses/gpl.txt).

MAILSTATS=`which mailstats 2>/dev/null`;
if [ "$1" == "-s" ]; then
	MULT=1
fi

if [ "$1" == "-m" ]; then
	MULT=60
fi

if [ -z "$MULT" ]; then
	printf "\nUsage: check_mailstats [-s|-m]\n"
	printf "	-s	Output performance data as mails per second\n"
	printf "	-m	Output performance data as mails per minute\n"
	exit
fi

if [ ! -e "$MAILSTATS" ]; then
	printf "CRITICAL - mailstats not found!\n"
	exit
fi

if [ ! -x "$MAILSTATS" ]; then
	printf "CRITICAL - mailstats doesn't have execute permission for current user\n"
	exit
fi

if [ ! -r "/var/log/sendmail.st" ]; then
	printf "CRITICAL - /var/log/sendmail.st has wrong permissions, should be 644\n"
	exit
fi

$MAILSTATS -P | awk -v mult=$MULT '/^ *T/ {
received = received + $4;
sent = sent + $2;
rejected = rejected + $6;
discarded = discarded + $7
} END {
print "OK - Total - Received:", received, "Sent:", sent, "Rejected:", rejected, "Discarded:", discarded, "| mails_rcvd="received*mult"c; mails_sent="sent*mult"c; mails_rjct="rejected*mult"c; mails_dscr="discarded*mult"c;"
}'