#! /usr/bin/python
# -*- coding: utf-8
#
# Monitors the number of printed pages
# ------------------------------------
#
# Written 2007 by Mario Kicherer (http://empanyc.net)
#
# environment parameters:
#
#	env.hp_printers - a list of the printernames, space seperated (f.e. printer1 printer2)
#	env.domain - the domain part (f.e. foo.com)
#	env.snmp_community - the community string for the SNMP query
#	env.host_name - optional hostname to display statistic in a seperated section (f.e. a special "Pool" section on the munin site)
#
#
# This script needs read permission for the following three SNMP entries:
#
#	- 1.3.6.1.2.1.43.10.2.1.4.1.1
#
# Version: 0.1 - Initial release
#
# Magic markers
#%# capabilities=autoconf
#%# family=contrib

import os,re,string,sys

def print_autoconf():
        print "yes"

def print_config():
	if (not host_name == ""):
		print "host_name "+host_name
        print "graph_title Total page counter"
        print "graph_vlabel Number of pages"
        print "graph_category Printer"
        print "graph_args --lower-limit 0"
	for printer in printers:
		print printer.replace("-","")+".label "+printer

def getpages(ip):
        ##############################
        ### query the total count of pages

	stdin, stdout, stderr = os.popen3(snmpwalk_cmd + ip + " 1.3.6.1.2.1.43.10.2.1.4.1.1")
        snmp_result = string.join(stdout.readlines())
        stdin.close();
        stdout.close();
        stderr.close();

        pages = "-1"
	result = re.search('SNMPv2-SMI::mib-2.43.10.2.1.4.1.1\s=\s([\d]+)', snmp_result)
        if result:
                pages = result.group(1)
        return int(pages)


##########
## main

if "snmp_community" in os.environ.keys():
        snmp_community = os.environ["snmp_community"]
else:
        snmp_community = "public"

snmpwalk_cmd = "snmpwalk -v1 -OQ -t 1 -r 0 -c " + snmp_community + " "

domain = ""
if "domain" in os.environ.keys():
	domain = "."+os.environ["domain"]

dns = {}
if "hp_printers" in os.environ.keys():
	printers = os.environ["hp_printers"]
	printers = printers.split(" ")
	for printer in printers:
		dns[printer] = printer+domain

if "host_name" in os.environ.keys():
	host_name = os.environ["host_name"]
else:
	host_name = ""

for parm in sys.argv:
        if parm == "autoconf":
                print_autoconf()
                sys.exit(0)
        if parm == "config":
                print_config()
                sys.exit(0)

pages = {}
for printer in printers:
	pages[printer] = getpages(dns[printer])
	if pages[printer] > -1:
		print printer.replace("-","") + ".value %i" % pages[printer]

