#!/bin/sh -e
#
# Copyright Emanuele Balla <skull@bofhland.org>
# Licenced under GPL v2
#
# Wildcard-plugin to gather per-zone queries stats from rbldnsd.
# To monitor a zone, link rbldnsd-zone_<zone> to this file. E.g.
#
#    ln -s /usr/local/share/munin/plugins/rbldnsd-zone_ /etc/munin/plugins/rbldnsd-zone_sbl.spamhaus.org
#
# ...will monitor sbl.spamhaus.org.
#
# This plugin monitors only queries stats, not the traffic (bytes in/out).
# At least, this is what it does *now*...
#
# Please note that rbldnsd needs to be set to log *absolute* values and not incremental ones
# (so use "-s stats.log" and not "-s +stats.log" in config file)
#
#
# $Log$
#
# Revision 1.0  2006/09/26 11:10:16  skull
# Basic functionalities: works for me and it's enough. Feel free to improve it... :-)
#
# Revision 1.1 2010/03/04 22:46:23 MdI
# Some compatibility improvements and a few less exec() needed
#
#
# Magic markers (optional - used by munin-config and some installation
# scripts):
#
#%# family=auto
#%# capabilities=autoconf

# Environment variables:
#	statsdir	directory where rbldnsd stats file is located
#	statsfile	name for the rbldnsd stats file 
#	pidfile		path to the rbldnsd pid file; defaults to /var/run/rbldnsd.pid

ZONE=`basename $0 | sed 's/^rbldnsd-zone_//g'`


if [ -z "$pidfile" ]; then
	pidfile="/var/run/rbldnsd.pid"
fi

if [ "$1" = "autoconf" ]; then
	if [ -f $statsdir/$statsfile ]; then
		echo yes
		exit 0
	else
		echo "no ($statsdir/$statsfile not found)"
		exit 1
	fi
fi

if [ "$1" = "config" ]; then

	echo "graph_title Stats for $ZONE"
	echo 'graph_args --base 1000 -l 0'
	echo 'graph_vlabel queries per ${graph_period}'
	echo 'graph_category rbldnsd'
	echo "graph_info This graph shows rbldnsd statistics for $ZONE zone."
	#
	echo 'qtot.label queries received'
	echo "qtot.info Queries received for $ZONE"
        echo 'qtot.type DERIVE'
        echo 'qtot.min 0'
	echo 'qok.label positive replies'
	echo "qok.info Positive replies for $ZONE"
        echo 'qok.type DERIVE'
        echo 'qok.min 0'
	echo 'qnxd.label negative replies'
	echo "qnxd.info Negative replies for $ZONE"
        echo 'qnxd.type DERIVE'
        echo 'qnxd.min 0'
	exit 0
fi

# Force rbldnsd to print its stats
read PIDFILE < $pidfile
kill -USR1 $PIDFILE 2> /dev/null || exit 1
# The line we read is done this way:
# 1159255472 sbl.spamhaus.org:8952822:336860:8615962:512296416:1001086269 xbl.spamhaus.org:882638:396463:486175:50214714:86301356 sbl-xbl.spamhaus.org:15066173:7215322:7850851:922977289:1520397665 *:25110851:7980272:17099508:1499757060:2627866686
statsline=`tail -n 1 $statsdir/$statsfile`

for item in $statsline; do
	zone=${item%%:*}
	[ "$zone" = "$ZONE" ] || continue
	rest=${item#*:}; qtot=${rest%%:*}
	rest=${rest#*:};  qok=${rest%%:*}
	rest=${rest#*:}; qnxd=${rest%%:*}
	rest=${rest#*:};  bin=${rest%%:*}
	rest=${rest#*:}; bout=${rest%%:*}
	echo "qtot.value $qtot"
	echo "qok.value $qok"
	echo "qnxd.value $qnxd"
	break
done

