#!/usr/bin/python
# Copyright (C) 2009  Glen Pitt-Pladdy
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
#
# See: http://www.pitt-pladdy.com/blog/_20100123-184109_0000_OpenWrt_with_native_IPv6_on_DG834_v2_using_AAISP_/
#


CACHETIME = 30
CACHEFILE = '/var/local/cacti/cache-openwrt-adsl-'


# get hostname (argument)
import os
import sys
try:
	HOST=sys.argv[1]
except:
	print os.path.basename(sys.argv[0])+": Requires hostname as argument"
	sys.exit ( 1 )
# extend CACHEFILE
CACHEFILE += HOST

# check for cache file newer CACHETIME seconds ago
import time
if os.path.isfile ( CACHEFILE ) \
	and ( time.time() - os.stat ( CACHEFILE )[8] ) < CACHETIME:
	# use cached data
	f = open ( CACHEFILE, 'r' )
	data = f.read()
	f.close()
else:
	# grab the status URL (fresh data)
	# need debian package python-urlgrabber
	from urlgrabber import urlread
	data = urlread ( 'http://'+HOST+'/cgi-bin/monitor/adsl',
					user_agent = 'OpenWRT Cacti Stats' )
	# write file
	f = open ( CACHEFILE+'.TMP.'+`os.getpid()`, 'w' )
	f.write ( data )
	f.close()
	os.rename ( CACHEFILE+'.TMP.'+`os.getpid()`, CACHEFILE )


# dice up the data
# the adsl staus is very inconsistent hence needs fiddly rules to makeit work
import re
params = {}
section = ''
subsection = ''
for line in data.splitlines():
	if re.search ( '^\[.+\]$', line ):
		# got a section
		section = line
		subsection = ''
#		print 'Section: '+section
	else:
#		print '---'
		fields = line.split( '\t' )
#		print fields
		if fields[0] == '':
			while len(fields) > 0 and fields[0] == '': fields.pop(0)
			if len(fields) == 0: continue
			if re.search ( '^\[.+\]$', fields[0] ):
				# subsection
				subsection = fields[0]
			else:
				# data fields
				while len(fields) > 0:
#					print fields
					while len(fields) > 0 and fields[0] == '': fields.pop(0)
					field = fields.pop(0)
					field = field.strip ( ': ' )
					field = field.replace ( '=', ':' )
					subfields = field.split( ':' )
					if ( len(subfields) > 1 ):
#						print 'Subfields:',
#						print subfields
						field = subfields[0]
						value = subfields[1]
					else:
#						print 'no subfields'
						while fields[0] == '': fields.pop(0)
#						print 'value = '+fields[0]
						value = fields.pop(0)
					if re.search ( '\d+ bps$', value ):
						value = re.sub ( ' bps$', '', value )
					elif re.search ( '\d+ kbps$', value ) \
						or field == 'US Connection Rate' \
						or field == 'DS Connection Rate':
						value = re.sub ( ' kbps$', '', value )
						value = str ( int ( value ) * 1024 )
					value = value.strip()
					value = value.replace ( ' ', '_' )
#					print section+subsection+field+' :: '+value
					params[section+subsection+field] = value



# output selected data
fieldstranslate = {
	'[DSL Modem Stats]DS Connection Rate':'ds_rate',
	'[DSL Modem Stats]US Connection Rate':'us_rate',
	'[DSL Modem Stats]DS Line Attenuation':'ds_atten',
	'[DSL Modem Stats]DS Margin':'ds_margin',
	'[DSL Modem Stats]US Line Attenuation':'us_atten',
	'[DSL Modem Stats]US Margin':'us_margin',
	'[DSL Modem Stats]DS Max Attainable Bit Rate':'ds_maxrate',
	'[DSL Modem Stats]US Max Attainable Bit Rate':'us_maxrate',
	'[DSL Modem Stats]Errored Seconds':'err_sec',
	'[DSL Modem Stats][Upstream (TX) Interleave path]CRC':'us_txint_crc',
	'[DSL Modem Stats][Downstream (RX) Interleave path]CRC':'ds_rxint_crc',
	'[DSL Modem Stats][Upstream (TX) Fast path]CRC':'us_txfast_crc',
	'[DSL Modem Stats][Downstream (RX) Fast path]CRC':'ds_rxfast_crc'
}
for param in fieldstranslate:
	print fieldstranslate[param]+':'+params[param],

# connectivity fields

if int(params['[Up Flag]Last Up']) < 300:
	# it was down and came up within the last sample
	print 'up:0.5',
	print 'down:0.5',
elif params['[DSL Modem Stats]DS Connection Rate'] == '0' \
	and params['[DSL Modem Stats]US Connection Rate'] == '0':
	print 'up:0',
	print 'down:1',
else:
	print 'up:1',
	print 'down:0',




