#!/bin/sh
# -*- sh -*-
#
# Plugin to monitor exim queue size
#
# Usage: Copy or link into /etc/munin/plugins/
#
# Parameters:
#
# 	config   (required)
# 	autoconf (optional - used by munin-config)
#
# Config variables:
#
# 	spooldir     - Override what exim says
# 	exim         - Where's exim?
# 	queuewarn    - When to warn
# 	queuecrit    - When to crit
#
# Magic markers (optional - used by installation scripts and
# munin-config):
#
#%# family=auto
#%# capabilities=autoconf

DIRNAME=$(dirname $0)
SPOOLDIR="unset"
# You cannot trust the exit status of which
EXIM=$(which exim 2>/dev/null)
case $EXIM:$? in
    *:1|no*) EXIM=$(which exim4 2>/dev/null)
esac
case $EXIM:$? in
    *:1|no*) EXIM=''
esac

GRAPHTITLE='Exim Mailqueue'

SPOOLDIR=${spooldir:-unset}
EXIM=${exim:-unset}
QUEUEWARN=${queuewarn:-100}
QUEUECRIT=${queuecrit:-200}
GRAPHTITLE=${graphtitle:-$GRAPHTITLE}

if [ "$SPOOLDIR" = "unset" ]
then
	SPOOLDIR=$( ($EXIM -bP spool_directory | awk '{ print $3 "/input" }') 2>/dev/null)
fi

if [ "$1" = "autoconf" ]; then
    if [ -z "$EXIM" ]; then
	echo no
	exit 1
    fi
	
	if $EXIM -bV 2>/dev/null >/dev/null; then
		if ( /usr/bin/find $SPOOLDIR -iname "*-H" -print 2>/dev/null >/dev/null ); then
			echo yes
			exit 0
		else
			if [ $? -eq 1 ]; then
				echo "no (permission denied on spooldir)"
				exit 1
			else
				echo "no"
				exit 1
			fi
		fi
	else
		if [ $? -eq 127 ]
		then
			echo "no (exim not found)"
			exit 1
		else
			echo no
			exit 1
		fi
	fi
fi

if [ "$1" = "config" ]; then
        if [ ! -z $SPOOLDIR ];then
	echo "graph_title $GRAPHTITLE"
	echo 'graph_args --base 1000 -l 0'
	echo 'graph_vlabel mails in queue'
	echo 'graph_category exim'
	echo 'mails.label mails'
	echo 'mails.draw AREA'
	echo "mails.warning $QUEUEWARN"
	echo "mails.critical $QUEUECRIT"
	fi;
	exit 0
fi

printf "mails.value "
/usr/bin/find $SPOOLDIR -iname "*-H" -print 2>/dev/null |wc -l | sed 's/ *//'
