#!/bin/sh
#
# Plugin to monitor postgresql commits
# 
#
# Parameters:
# 	
# 	config
# 	autoconf
#
# Configuration variables
#
#	PGHOST
#	PGPORT
#	PGDATABASE
#	PGUSER
#
#	(See libpq documentation for more.)
#	Note that PGDATABASE will default to 'template1' in this plugin, and
#	without PGHOST it will try ident authentication with the local server,
#	as the user that the plugin is running as.
#
# Configuration example:
#
#	# Use local server, ident authentication with the 'postgres' user.
#	[postgres_*]
#	user postgres
#
#	# Use local server, TCP authentication with a username and password.
#	[postgres_*]
#	env.PGHOST localhost
#	env.PGUSER someuser
#	env.PGPASSWORD somepassword
#
# Revision history:
#
# 2005-10-03 v0.0001  Vajtsz
#	this is my first munin plugin sorry for dummy code
# 2007-12-14 v0.0002  Tim Retout <tim.retout@credativ.co.uk>
#	Use libpq environment variables for configuration. Document the two
#	most common cases.
#
#
#
#%# family=auto
#%# capabilities=autoconf

# It is not guaranteed that a database exists with the same name as the user,
# but template1 should generally be there.
if [ -z "$PGDATABASE" ]; then
	PGDATABASE="template1"
fi

psql_comm='psql -c'

if [ "$1" = "autoconf" ]; then
        psql  --version 2>/dev/null >/dev/null
        if [ $? -eq 0 ]
        then
                $psql_comm  2>/dev/null >/dev/null
                if [ $? -eq 0 ]
                then
                        echo yes
                        exit 0
                else
                        echo "no (could not connect to psql)"
                fi
        else
                echo "no (psql not found)"
        fi
        exit 1
fi

if [ "$1" = "config" ]; then
	echo 'graph_title PostgreSQL common'
	echo 'graph_vlabel Count'
	echo 'graph_category PostgreSQL '
	echo 'graph_args --base 1000'
	echo 'backends.label Backend count'
	echo 'backends.draw LINE2'	
	echo 'backends.type COUNTER'			
	echo 'commits.label Commit count'	
	echo 'commits.draw LINE2'		
	echo 'commits.type COUNTER'			
	echo 'rollbacks.label Rollback count'	
	echo 'rollbacks.draw LINE2'		
	echo 'rollbacks.type COUNTER'	

	exit 0
fi

ebbe=`$psql_comm 'select sum(numbackends) from pg_stat_database'`
ebbe1=`echo $ebbe | awk '{print($3)}'`
/usr/bin/printf "backends.value $ebbe1\n"
ebbe=`$psql_comm 'select sum(xact_commit),sum(xact_rollback) from pg_stat_database'`
ebbe1=`echo $ebbe | awk '{print($5)}'`
ebbe2=`echo $ebbe | awk '{print($7)}'`
/usr/bin/printf "commits.value $ebbe1\n"
/usr/bin/printf "rollbacks.value $ebbe2\n"
