#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2015             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.


import os, sys, getopt, subprocess


def usage():
    sys.stderr.write("""Check_MK IPMI Sensors

USAGE: agent_ipmi_sensors [OPTIONS] HOST
       agent_ipmi_sensors --help

ARGUMENTS:
  HOST                        Host name or IP address

OPTIONS:
  --help                      Show this help message and exit
  -u                          Username
  -p                          Password
  -l                          Privilege level
                              Possible are 'user', 'operator', 'admin'
  --debug                     Debug output
""")


short_options = 'u:p:l:'
long_options  = [ 'help', 'debug' ]


opt_debug      = False
hostname       = None
username       = None
password       = None
privilege_lvl  = None


try:
    opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
except getopt.GetoptError, err:
    sys.stderr.write("%s\n" % err)
    sys.exit(1)


for o, a in opts:
    if o in [ '--help' ]:
        usage()
        sys.exit(0)
    elif o in [ '--debug' ]:
        opt_debug = True
    elif o in [ '-u' ]:
        username = a
    elif o in [ '-p' ]:
        password = a
    elif o in [ '-l' ]:
        privilege_lvl = a


if len(args) == 1:
    hostname = args[0]
elif not args:
    sys.stderr.write("ERROR: No host given.\n")
    sys.exit(1)
else:
    sys.stderr.write("ERROR: Please specify exactly one host.\n")
    sys.exit(1)


if not (username and password and privilege_lvl):
    sys.stderr.write("ERROR: Credentials are missing.\n")
    sys.exit(1)


for sub_path in [ "sbin", "bin", "local/sbin", "local/bin" ]:
    base_cmd = "/usr/%s/ipmi-sensors" % sub_path
    ipmi_cmd = [base_cmd, "-h", hostname, "-u", username, "-p", password, "-l", privilege_lvl ]
    try:
        if opt_debug:
            sys.stdout.write("DEBUG: try executing '%s'\n" % base_cmd)
        p = subprocess.Popen(ipmi_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        sensor_data, err = p.communicate()
        break
    except Exception, e:
        err = e
        if opt_debug:
            sys.stdout.write("ERROR: '%s': %s\n" % (base_cmd, e))
        continue


# output
# ID   | Name            | Type              | Reading    | Units | Event
# 4    | CPU Temp        | Temperature       | 28.00      | C     | 'OK'
# 71   | System Temp     | Temperature       | 28.00      | C     | 'OK'
# 607  | P1-DIMMC2 TEMP  | Temperature       | N/A        | C     | N/A


def parse_ipmi_sensor_data(ipmi_sensor_data):
    for line in ipmi_sensor_data:
        if line.startswith("ID"):
            continue
        else:
            sensor_id, sensor_name, sensor_type, reading, unit, event = \
                map(lambda x: x.strip().replace(" ", "_").replace("/", ""), line.split("|"))
            sys.stdout.write("%s %s_%s %s_%s_(NA/NA) [%s]\n" % \
                  (sensor_id, sensor_type, sensor_name,
                   reading, unit, event.replace("'", "")))


if err:
    sys.stderr.write("ERROR: '%s'\n" % err[:-1])
    sys.exit(1)
else:
    sys.stdout.write("<<<ipmi_sensors>>>\n")
    parse_ipmi_sensor_data(sensor_data.splitlines())
    sys.exit(0)
