#!/usr/bin/python
#
# Author: Sascha Curth
#
import urllib
import json
import sys
import os

scriptname=os.path.basename(__file__)

parts=scriptname.split('_')

if ( len(parts) != 5 ):
    print "Please append the API IP to the scriptname, e.g. YOCTOUSBPOWER_127_0_0_1"
    exit()

realIP ="%s.%s.%s.%s" % (parts[1],parts[2],parts[3],parts[4])
apiuri='http://%s:4444' % realIP

def initDeviceinfo(networkUrl):
    deviceurl = '%s%s.json' % (apiuri,networkUrl)
    deviceresponse = urllib.urlopen(deviceurl)
    devicedata = json.loads(unicode(deviceresponse.read(),'latin-1'))
    return devicedata

if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
    #Magic markers for munin autoconf
    #%# family=auto
    #%# capabilities=autoconf suggest
    print "yes"
elif len(sys.argv) >= 2 and sys.argv[1] == "suggest":
    print scriptname

elif len(sys.argv) == 2 and sys.argv[1] == "config":
    huburl = '%s/api.json' % apiuri
    hubresponse = urllib.urlopen(huburl);
    hubdata = json.loads(unicode(hubresponse.read(),'latin-1'))
    print 'graph_title %s' % (hubdata["module"]["serialNumber"])
    print 'graph_vlabel Power Consumption'
    print 'graph_category yoctopuce'
    for key in hubdata["services"]["whitePages"]:
        val=key["serialNumber"].replace('-','_')
        if val.find("VIRTHUB") == -1:
            print '%s.label power consumption of %s in mA' % (val,val)
            print '%s.draw AREASTACK' % (val)
            print '%s.type GAUGE' % (val)
            for thresholdtype in ["warning","critical"]:
                varname="%s.%s" % (val,thresholdtype)
                if os.environ.get(varname) is not None:
                    print '%s %s' % (varname,os.environ.get(varname))


else:
    huburl = '%s/api.json' % apiuri
    hubresponse = urllib.urlopen(huburl);
    hubdata = json.loads(unicode(hubresponse.read(),'latin-1'))
    for key in hubdata["services"]["whitePages"]:
        val=key["serialNumber"]
        if val.find("VIRTHUB") == -1:
            devicedata=initDeviceinfo(key["networkUrl"])
            print '%s.value %s' % (val.replace('-','_'),devicedata["module"]["usbCurrent"])


