#!/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.acme import *  # pylint: disable=wildcard-import,unused-wildcard-import
# comNET GmbH, Fabian Binder

# .1.3.6.1.4.1.9148.3.2.1.1.3 Health Score (apSysHealthScore)
# .1.3.6.1.4.1.9148.3.2.1.1.4 Health Status Description (apSysRedundancy)

factory_settings["acme_sbc_snmp_default_levels"] = {
    "levels_lower": (99, 75),
}


def inventory_acme_sbc_snmp(info):
    yield None, {}


def check_acme_sbc_snmp(_no_item, params, info):
    map_states = {
        "0": (3, "unknown"),
        "1": (1, "initial"),
        "2": (0, "active"),
        "3": (0, "standby"),
        "4": (2, "out of service"),
        "5": (2, "unassigned"),
        "6": (1, "active (pending)"),
        "7": (1, "standby (pending)"),
        "8": (1, "out of service (pending)"),
        "9": (1, "recovery"),
    }

    try:
        score, state = info[0]
    except (IndexError, ValueError):
        return
    health_state, health_state_readable = map_states.get(state, (3, "unknown"))
    yield health_state, "Health state: %s" % (health_state_readable)

    try:
        score = int(score)
    except ValueError:
        yield 3, "Unknown score: %s" % score
        return
    warn, crit = params.get("levels_lower", (None, None))
    levels_msg = " (warn/crit at or below %s%%/%s%%)" % (warn, crit)
    score_msg = "Score: %s%%" % score
    if crit is not None and score <= crit:
        yield 2, score_msg + levels_msg
    elif warn is not None and score <= warn:
        yield 1, score_msg + levels_msg
    else:
        yield 0, score_msg


check_info['acme_sbc_snmp'] = {
    'inventory_function': inventory_acme_sbc_snmp,
    'check_function': check_acme_sbc_snmp,
    'service_description': 'ACME SBC health',
    'snmp_info': (
        '.1.3.6.1.4.1.9148.3.2.1.1',
        [
            "3",  # APSYSMGMT-MIB::apSysHealthScore
            "4",  # APSYSMGMT-MIB::apSysRedundancy
        ]),
    'snmp_scan_function': scan_acme,
    'group': 'acme_sbc_snmp',
    'default_levels_variable': 'acme_sbc_snmp_default_levels',
}
