#!/usr/bin/python
# encoding: utf-8
#
# munin-plugin for temper
#
# Copyright 2013 Alexander Schier <allo@laxu.de>
# 
# This code is licensed under the GNU public license (GPL). See LICENSE.md for details.

#%# capabilities=autoconf

from __future__ import print_function
import sys


def get_handler():
    from temperusb.temper import TemperHandler
    return TemperHandler()


def autoconf():
    try:
        handler = get_handler()
    except ImportError:
        print ("no (temper-python package is not installed)")
    else:
        if len(handler.get_devices()):
            print ("yes")
        else:
            print ("no (No devices found)")


def config():
    handler = get_handler()
    print ("graph_title Temperature")
    print ("graph_vlabel Degrees Celsius")
    print ("graph_category sensors")
    for device in handler.get_devices():
        port = device.get_ports()
        port_name = str(port).replace('.', '_')
        print ("temp_" + port_name + ".label Port {0:s} Temperature".format(str(port)))


def fetch():
    handler = get_handler()
    for device in handler.get_devices():
        port = device.get_ports()
        port_name = str(port).replace('.', '_')
        try:
            temp = device.get_temperature()
        except Exception:
            temp = 'U'
        print ("temp_" + port_name + ".value {0:f}".format(temp))


def main():
    if len(sys.argv) == 2:
        arg = sys.argv[1]
        if arg == 'autoconf':
            autoconf()
        elif arg == 'config':
            config()
    else:
        fetch()
    sys.exit(0)    
  
       
if __name__ == '__main__':
    main()
