#!/bin/sh

# Copyright (C) 2009 Andreas Thienemann <andreas@bawue.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Library General Public License as published by
# the Free Software Foundation; version 2 only
#
# 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 Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

# 
# Plugin to monitor the load on a cyrus imapd server
#
# Usage: Link or copy into the munin-node plugin directory
#
# Installation node: Should most likely run as root:
# [cyrus-imapd]
# user root
#
#
# Magic markers (optional - only used by munin-config and some
# installation scripts):
#
#%# family=contrib
#%# capabilities=autoconf

# IMAP Configuration Directory
CONFIGDIR=$(awk -F : '/^configdirectory:/ { gsub(/ /, "", $2); print $2 }' /etc/imapd.conf 2> /dev/null)
PROCDIR="${CONFIGDIR}/proc"

if [ "$1" = "autoconf" ]; then
	if [ "x${CONFIGDIR}x" != "xx" ] && [ -d ${PROCDIR} ]; then
		echo yes
	else
		echo no
	fi
	exit 0
fi

# Check if we actually got some sensible data
if [ "x${CONFIGDIR}x" == "xx" ]; then
	exit 1
fi

# If run with the "config"-parameter, give out information on how the
# graphs should look. 
 
if [ "$1" = "config" ]; then
	echo 'graph_title Cyrus IMAPd Load'
	echo 'graph_args --base 1000 -l 0'
	echo 'graph_vlabel connections'
	echo 'graph_scale no'
	echo 'graph_category cyrus'
	echo 'graph_info Current connections to the imap server. <a href="http://trac.bawue.org/">bawue.net e.V. Trac repository</a>.'
	echo 'graph_oder connections authenticated_users unique_users'
	echo 'connections.label Connections'
	echo 'connections.info Number of connections to the imap server.'
	echo 'authenticated_users.label Authenticated Users'
	echo 'authenticated_users.info Number of authenticated users logged into the imap server.'
	echo 'unique_users.label Unique Users'
	echo 'unique_users.info Number of unique users on the imap server.'

	# Last, if run with the "config"-parameter, quit here (don't
	# display any data)
	exit 0
fi

# Print the number of connections to the imap server
echo -n "connections.value "
ls ${PROCDIR} | wc -l

# Read the proc files and get the logged in users
echo -n "authenticated_users.value "
awk '{ split(substr($0, match($0, "]")+1), a); if (a[1] != "") print a[1] }' ${PROCDIR}/* | wc -l

# Read the proc files and get the number of unique users
echo -n "unique_users.value "
awk '{ split(substr($0, match($0, "]")+1), a); if (a[1] != "") print a[1] }' ${PROCDIR}/* | sort -u | wc -l

