#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Monitor Voltages
#
# Author: Mathias Ertl <mati@fsinf.at>
#
#%# family=auto
#%# capabilities=autoconf

import os
import re
import sys

from subprocess import PIPE
from subprocess import Popen


if len(sys.argv) > 1 and sys.argv[1] == 'autoconf':
    """
    We support autoconf. Please see:
        http://munin.projects.linpro.no/wiki/ConcisePlugins#autoconf
    """
    p = Popen(['which', 'sensors'], text=True, stdout=PIPE)
    p.communicate()
    if p.returncode == 0:
        print('yes')
        sys.exit(0)
    else:
        print('no (sensors not found)')
        sys.exit(1)


def sanitize_name(string):
    for regexp in ['^[^A-Za-z_]', '[^A-Za-z0-9_]']:
        string = re.compile(regexp).sub('_', string)
    return string

config = False
if len(sys.argv) > 1 and sys.argv[1] == 'config':
    """
    Print the config-header. Note that field labels are printed in the loop
    below.
    """
    config = True
    print """graph_category sensors
graph_title Voltages
graph_args --base 1000 -l 0
graph_vlabel Volt
graph_scale no
graph_info Monitor voltages as captured by lm-sensors."""

p = Popen(['sensors'], text=True, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate()
retval = p.returncode

# Various fields may be excluded with the "ignore" environment variable.
ignores = os.environ.get('ignore')
if ignores:
    ignores = ignores.split()
else:
    ignores = []


for line in stdout.split("\n"):
    """
    Actually print the fields
    """

    if len(line) > 1 and line.find(':') == -1:
        """This is a chip"""
        chip = line
        continue

    if line.find(' V ') == -1:
        """Not a voltage"""
        continue

    label, rest = line.split(':', 1)
    fieldname = sanitize_name("%s_%s" % (chip, label))

    if fieldname in ignores:
        continue

    if config:
        print("%s.label %s" % (fieldname, label))
        for limit in ['warning', 'critical', 'info']:
            """get additional info from environment variables"""
            var = os.environ.get("%s_%s" % (fieldname, limit))
            if var:
                print("%s.%s %s" % (fieldname, limit, var))
    else:
        value = rest.strip().split()[0]
        print("%s.value %s" % (fieldname, value))
