#!/usr/bin/env python
from commands import getstatusoutput as gso

def safe(s):
    s=s.replace("-", "_")
    s=s.replace(" ", "_")
    s=s.replace(".", "_")
    return s

def config(data,title):
    for i in data:
        print "%s.label %s"%(safe(i[0]), i[0])

        # check for non-critical thresholds
        if i[6] != 'na':
            if i[7] != 'na':
                warning = "%s:%s"%(i[6],i[7])
            else:
                warning = "%s:"%i[6]
        else:
            if i[7] != 'na':
                warning = "%s"%i[7]
            else:
                warning = ""
        if warning:    
            print "%s.warning %s"%(safe(i[0]),warning)

        # check for critical thresholds
        if i[5] == 'na':
            i[5] == i[4] # N/A, so see if there is a non-recoverable threshold
        if i[8] == 'na':
            i[8] == i[9] # N/A, so see if there is a non-recoverable threshold
        if i[5] != 'na':
            if i[8] != 'na':
                critical = "%s:%s"%(i[5],i[8])
            else:
                critical = "%s:"%i[5]
        else:
            if i[8] != 'na':
                critical = "%s"%i[8]
            else:
                critical = ""
        if critical:    
            print "%s.critical %s"%(safe(i[0]),critical)

    print "graph_title %s"%title
    if title == "Voltages":
        print "graph_args -X 0 --logarithmic -l 1 -u 15"
        #print "graph_args --base 1000 --logarithmic"
    else:
        print "graph_args -l 0"
    print "graph_vlabel %s"%i[2]
    print "graph_period minute"
    print "graph_category IPMI"

def get_data():
    import sys
    category = sys.argv[0].split("_",1)[1]
    data = []
    if category =="Fans":
        ids = ("Fan 1 Tach", "Fan 2 Tach", "Fan 3 Tach",
               "Fan 4 Tach", "Fan 5 Tach", "Fan 6 Tach",)
        title = "Fan Speed"
    elif category == "Temperature":
        ids = ("Ambient Temp", "Memory Temp",)
        title = "Temperatures"
    elif category == "Voltage":
        ids = ("Planar 1.5V", "Planar 1.8V",
              "Planar 3.3V", "Planar 5V", "Planar 12V",
              "Planar VBAT", "CPU 1 VCore", "CPU 2 VCore",)
        title = "Voltages"

    status, output = gso("ipmitool sensor")
    for row in output.split("\n"):
        items = map(str.strip,row.split("|"))
        field,value,units,status,lower_nonrecoverable,lower_critical,lower_non_critical,upper_non_critical,upper_critical,upper_nonrecoverable=items
        if field in ids:
            if value == 'na': continue
            data.append(items)
    return data,title

def sample(data):
    for i in data:
        print "%s.value %s"%(safe(i[0]),i[1])

def main():
    import sys
    data,title = get_data()
    if 'config' in sys.argv:
        return config(data,title)
    sample(data)

if __name__ == '__main__':
    main()

