#!/bin/bash
#
# 19-07-2010
# Author: Cherwin Nooitmeer <cherwin@gmail.com>
#
# added output strings OK, Warning, CRITICAL and Unknown
# added -f (filesystem mode: count queue files directly in postfix's
# spool directory instead of parsing mailq's formatted output; faster on
# large queues, but needs read access to the spool directory) and -d
# (postfix spool directory, default /var/spool/postfix)

# exit codes
e_ok=0
e_warning=1
e_critical=2
e_unknown=3

# regular expression that matches queue IDs (e.g. D71EF7AC80F8)
#queue_id='^[A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9]'
queue_id='^[0-9A-F]{9,16}'

spooldir='/var/spool/postfix'
filesystem_mode=0

usage="Invalid command line usage"

if [ -z $1 ]; then
    echo $usage
    echo "UNKNOWN"
    exit $e_unknown
fi

while getopts ":w:c:fd:" options
do
    case $options in
        w ) warning=$OPTARG ;;
        c ) critical=$OPTARG ;;
        f ) filesystem_mode=1 ;;
        d ) spooldir=$OPTARG ;;
        * ) echo $usage
	    echo "UNKNOWN"
            exit $e_unknown ;;
    esac
done

# determine queue size
if [ $filesystem_mode -eq 1 ]; then
    # same queues mailq reports on: incoming, active, deferred and hold
    # (excludes maildrop, which is pre-queue, and corrupt, which mailq
    # does not report either)
    qsize=$(find "$spooldir"/incoming "$spooldir"/active "$spooldir"/deferred "$spooldir"/hold -type f 2>/dev/null | wc -l)
else
    qsize=$(mailq | egrep -c $queue_id)
fi
if [ -z $qsize ]
then
    echo "UNKNOWN"
    exit $e_unknown
fi

if [ $qsize -ge $critical ]; then
    retval=$e_critical
    echo -n "CRITICAL - "
elif [ $qsize -ge $warning ]; then
    retval=$e_warning
    echo -n "WARNING - "
elif [ $qsize -lt $warning ]; then
    retval=$e_ok
    echo -n "OK - "
fi

echo "$qsize mail(s) in queue | mail_queue=$qsize"
exit $retval
