#!/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) < 6 ):
    print "Please append the API IP to the scriptname, e.g. YOCTOPUCE_127_0_0_1_"
    exit()

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

if ( len(parts) > 6):
    modulename="%s" % parts[5]
    serial="%s" % parts[6]
    measurementtype="%s" % parts[7]

def initDeviceinfo():
    deviceurl = '%s/bySerial/%s-%s/api.json' % (apiuri,modulename,serial)
    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":
    huburl = '%s/api.json' % apiuri
    hubresponse = urllib.urlopen(huburl);
    hubdata = json.loads(unicode(hubresponse.read(),'latin-1'))
    for key in hubdata["services"]["yellowPages"]:
        if key not in ["DataLogger","Network","Relay","HubPort","Files"]:
            for measurementtype in hubdata["services"]["yellowPages"][key]:
                if (key == "Power"):
                    print "%s_cosPhi" % measurementtype["hardwareId"].replace('-','_').replace('.','_')
                if len(sys.argv) == 3 and sys.argv[2] == "env":
                    prefix='  env.'
                    print "[%s_%s]" % (scriptname.partition('_')[0],measurementtype["hardwareId"].replace('-','_').replace('.','_'))
                    suffix='.warning 0'
                    print "%s%s%s" % (prefix,measurementtype["hardwareId"].partition('.')[2],suffix)
                    suffix='.critical 0'
                    print "%s%s%s" % (prefix,measurementtype["hardwareId"].partition('.')[2],suffix)
                    print ''
                else:
                    print "%s" % measurementtype["hardwareId"].replace('-','_').replace('.','_')

elif len(sys.argv) == 2 and sys.argv[1] == "config":
    devicedata=initDeviceinfo()
    logicalname=devicedata["module"]["logicalName"]
    print 'graph_title %s %s' % (scriptname,logicalname)
    print 'graph_category yoctopuce'
    
    if os.environ.get('vlabel'):
        print 'graph_vlabel %s' % (os.environ.get('vlabel'))
        print '%s.label Current value in %s' % (measurementtype,(os.environ.get('unit')))
    else:
        if (len(parts) == 9):
        # key specified manually
            print 'graph_vlabel %s_%s' % (parts[7],parts[8])
            print '%s.label raw value of %s' % (measurementtype,parts[8])
        else:
            print 'graph_vlabel %s in %s' % (''.join(measurementtype[0].upper() + measurementtype[1:]),devicedata[measurementtype]["unit"])
            print '%s.label Current value in %s' % (measurementtype,devicedata[measurementtype]["unit"])

    varname="%s.draw" % measurementtype
    if os.environ.get(varname) is None:
        draw='LINE1'
    else:
        draw=os.environ.get(varname)
    print '%s.draw %s' % (measurementtype,draw)
    varname="%s.type" % measurementtype
    if os.environ.get(varname) is None:
        mtype='GAUGE'
    else:
        mtype=os.environ.get(varname)
    print '%s.type %s' % (measurementtype,mtype)
    for thresholdtype in ["warning","critical"]:
        varname="%s.%s" % (measurementtype,thresholdtype)
        if os.environ.get(varname) is not None:
            print '%s %s' % (varname,os.environ.get(varname))

else:
    devicedata=initDeviceinfo()
# to access keys other then "advertisedValue", the key name need to be specified, e.g. YOCTOPUCE_10_0_1_17_YWATTMK1_20975_power_cosPhi
    if (len(parts) == 9):
        key=parts[8]
    else:
        key="advertisedValue"

    if os.environ.get('convertformula'):
        convertedValue = eval(os.environ.get('convertformula'))
        print '%s.value %.1f' % (measurementtype,convertedValue)
    else:
        print '%s.value %s' % (measurementtype,devicedata[measurementtype][key])
