#!/usr/bin/python
# ADSL connection speed and noise levels plugin for a Netgear 
#  DG834G or similar
#
# Requires that telnet is enabled on the router - go to
#   http://<router>/setup.cgi?todo=debug
#  eg http://192.168.1.1/setup.cgi?todo=debug
# to enable it
#
# This plugin should be symlinked in as one of:
#     dg834g_adsl_speed
#     dg834g_adsl_noise

import os
import re
import sys
from telnetlib import Telnet

# Make sure we got the host to talk to
if not os.environ.has_key("host"):
	print "Environment host not given"
	print "This program must be run with the DG834G hostname set"
	print ""
	print "Try adding to /etc/munin/munin-node.conf something like:"
	print ""
	print "[dg834g_adsl]"
	print "env.host 192.168.1.1"
	sys.exit(1)
host = os.environ["host"]

def invalid_cmd(given):
	print "Error - must be called one of:"
	print "    dg834g_adsl_speed"
	print "    dg834g_adsl_noise"
	if given:
		print ""
		print "Option \"%s\" not recognised" % given
	sys.exit(1)

# How are they calling us?
cmd = re.search("dg834g_adsl_(\w+)", sys.argv[0])
if not cmd:
	invalid_cmd(None)
mode = cmd.groups(1)[0]

# Config mode
if len(sys.argv) > 1 and sys.argv[1] == "config":
	print "graph_title ADSL Connection %s for %s" % (mode, host)
	print "graph_category network"
	print "graph_args --base 1024 -l 0"
	print "graph_scale no" # for now, don't turn into k/m automatically
	if mode == "speed":
		print "graph_vlabel kbps"
		print "graph_info The upstream and downstream ADSL connection speeds"
		print "upstream.label Upstream speed"
		print "downstream.label Downstream speed"
	elif mode == "noise":
		print "graph_vlabel dB"
		print "graph_info The upstream and downstream ADSL connection attenuation and signal/noise ratio"
		print "upstream_snr.label Upstream SNR"
		print "upstream_attn.label Upstream Attenuation"
		print "downstream_snr.label Downstream SNR"
		print "downstream_attn.label Downstream Attenuation"
	else:
		invalid_cmd(mode)
else:
	if mode == "speed":
		data_re = re.compile("Upstream rate = (\d+) Kbps, Downstream rate = (\d+) Kbps")
	elif mode == "noise":
		data_re = re.compile("SNR \(dB\):\s+(\d+\.\d+)\s+(\d+\.\d+)\s*Attn\(dB\):\s+(\d+\.\d+)\s+(\d+\.\d+)")
	else:
		invalid_cmd(mode)

	t = Telnet(host, 23)
	t.read_until("#", 10)
	t.write("adslctl info --stats\n")
	info = t.read_until("#", 10)
	t.write("exit\n")
	t.read_all()

	data = data_re.search(info)

	if data:
		if mode == "speed":
			print "upstream.value %s" % data.group(1)
			print "downstream.value %s" % data.group(2)
		elif mode == "noise":
			print "downstream_snr.value %s" % data.group(1)
			print "upstream_snr.value %s" % data.group(2)
			print "downstream_attn.value %s" % data.group(3)
			print "upstream_attn.value %s" % data.group(4)
		else:
			invalid_cmd(mode)
	else:
		print info
		sys.exit(1)
