#! /bin/bash
#
# Munin Plugin
# to count logins to your dovecot mailserver
#
# Created by Dominik Schulz <lkml@ds.gauner.org>
# http://developer.gauner.org/munin/
# Contributions by:
# - Stephane Enten <tuf@delyth.net>
# - Steve Schnepp <steve.schnepp@pwkf.org>
# - pcy <pcy@ulyssis.org> (make 'Connected Users' DERIVE, check existence of logfile in autoconf)
#
# Parameters understood:
#
#	config		(required)
#	autoconf 	(optional - used by munin-config)
#
# Config variables:
#
#       logfile        - Where to find the syslog file
#
# Add the following line to a file in /etc/munin/plugin-conf.d:
# 	env.logfile /var/log/your/logfile.log
#
# Magic markers (optional - used by munin-config and installation scripts):
#
#%# family=auto
#%# capabilities=autoconf

######################
# Configuration
######################
EXPR_BIN=/usr/bin/expr
LOGFILE=${logfile:-/var/log/mail.log}
######################

if [ "$1" = "autoconf" ]; then
	[ -f "$LOGFILE" ] && echo yes || echo "no (logfile $LOGFILE not found)"
	exit 0
fi

if [ "$1" = "config" ]; then
	echo 'graph_title Dovecot Logins'
	echo 'graph_category mail'
	echo 'graph_args --base 1000 -l 0'
	echo 'graph_vlabel Login Counters'

	for t in Total TLS SSL IMAP POP3
	do
		field=$(echo $t | tr '[:upper:]' '[:lower:]')
		echo "login_$field.label $t Logins"
		echo "login_$field.type DERIVE"
		echo "login_$field.min 0"
	done

	echo 'connected.label Connected Users'
	echo "connected.type DERIVE"

	exit 0
fi

######################
# Total Logins
######################
echo -en "login_total.value "
VALUE=$(egrep -c '[dovecot]?.*Login' $LOGFILE)
if [ ! -z "$VALUE" ]; then
	echo "$VALUE"
else
	echo "0"
fi
echo -n
######################
# Connected Users
######################
DISCONNECTS=$(egrep -c '[dovecot]?.*Disconnected' $LOGFILE)
CONNECTS=$(egrep -c '[dovecot]?.*Login' $LOGFILE)
VALUE=$($EXPR_BIN $CONNECTS - $DISCONNECTS)
if [ -z "$VALUE" ] || [ "$VALUE" -lt 0 ]; then
	VALUE=0
fi
echo -en "connected.value "
echo $VALUE
echo -n
######################
# TLS Logins
######################
echo -en "login_tls.value "
VALUE=$(egrep -c '[dovecot]?.*Login.*TLS' $LOGFILE)
if [ ! -z "$VALUE" ]; then
	echo "$VALUE"
else
	echo "0"
fi
echo -n
######################
# SSL Logins
######################
echo -en "login_ssl.value "
VALUE=$(egrep -c '[dovecot]?.*Login.*SSL' $LOGFILE)
if [ ! -z "$VALUE" ]; then
	echo "$VALUE"
else
	echo "0"
fi
echo -n
######################
# IMAP Logins
######################
echo -en "login_imap.value "
VALUE=$(egrep -c '[dovecot]?.*imap.*Login' $LOGFILE)
if [ ! -z "$VALUE" ]; then
	echo "$VALUE"
else
	echo "0"
fi
echo -n
######################
# POP3 Logins
######################
echo -en "login_pop3.value "
VALUE=$(egrep -c '[dovecot]?.*pop3.*Login' $LOGFILE)
if [ ! -z "$VALUE" ]; then
	echo "$VALUE"
else
	echo "0"
fi
echo -n
