#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.blade_scan import *  # pylint: disable=wildcard-import,unused-wildcard-import


def inventory_blade_powerfan(info):
    return [(line[0], '(50, 40)') for line in info if line[0] != '' and line[1] == '1']


def check_blade_powerfan(item, params, info):
    warn_perc, crit_perc = params
    for index, present, status, _fancount, speedperc, rpm, ctrlstate in info:
        if index != item:
            continue
        perfdata = [('perc', speedperc, warn_perc, crit_perc, "0", "100"), ('rpm', rpm)]
        speedperc_int = saveint(speedperc)
        if present != "1":
            return (2, "Fan not present", perfdata)
        elif status != "1":
            return (2, "Status not OK", perfdata)
        elif ctrlstate != "0":
            return (2, "Controller state not OK", perfdata)
        elif speedperc_int <= crit_perc:
            return (2, "Speed at %d%% of max (crit at %d%%)" % (speedperc_int, crit_perc), perfdata)
        elif speedperc_int <= warn_perc:
            return (1, "Speed at %d%% of max (warning at %d%%)" % (speedperc_int, warn_perc),
                    perfdata)
        return (0, "Speed at %s RPM (%d%% of max)" % (rpm, speedperc_int), perfdata)

    return (3, "Device %s not found in SNMP data" % item)


check_info["blade_powerfan"] = {
    'check_function': check_blade_powerfan,
    'inventory_function': inventory_blade_powerfan,
    'service_description': 'Power Module Cooling Device %s',
    'has_perfdata': True,
    'snmp_info': ('.1.3.6.1.4.1.2.3.51.2.2.6.1.1', [1, 2, 3, 4, 5, 6, 7]),
    'snmp_scan_function': scan_blade_power_modules,
}
