#!/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.mem import *  # pylint: disable=wildcard-import,unused-wildcard-import
# 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.ucd_hr import *  # pylint: disable=wildcard-import,unused-wildcard-import
# FIXME
# The WATO group 'memory_simple' needs an item and the service_description should
# have a '%s'.  At the moment the current empty item '' and 'Memory' without '%s'
# works but is not consistent.  This will be fixed in the future.
# If we change this we loose history and parameter sets have to be adapted.

# .1.3.6.1.4.1.2021.4.2.0 swap      --> UCD-SNMP-MIB::memErrorName.0
# .1.3.6.1.4.1.2021.4.3.0 8388604   --> UCD-SNMP-MIB::MemTotalSwap.0
# .1.3.6.1.4.1.2021.4.4.0 8388604   --> UCD-SNMP-MIB::MemAvailSwap.0
# .1.3.6.1.4.1.2021.4.5.0 4003584   --> UCD-SNMP-MIB::MemTotalReal.0
# .1.3.6.1.4.1.2021.4.11.0 12233816 --> UCD-SNMP-MIB::MemTotalFree.0
# .1.3.6.1.4.1.2021.4.12.0 16000    --> UCD-SNMP-MIB::memMinimumSwap.0
# .1.3.6.1.4.1.2021.4.13.0 3163972  --> UCD-SNMP-MIB::memShared.0
# .1.3.6.1.4.1.2021.4.14.0 30364    --> UCD-SNMP-MIB::memBuffer.0
# .1.3.6.1.4.1.2021.4.15.0 10216780 --> UCD-SNMP-MIB::memCached.0
# .1.3.6.1.4.1.2021.4.100.0 0       --> UCD-SNMP-MIB::memSwapError.0
# .1.3.6.1.4.1.2021.4.101.0         --> UCD-SNMP-MIB::smemSwapErrorMsg.0

# suggested by customer
factory_settings["ucd_mem_default_levels"] = {
    "levels": ("perc_used", (80.0, 90.0)),
    "swap_errors": 0
}


def parse_ucd_mem(info):
    # this should never happen
    raise RuntimeError("section is already migrated")


def inventory_ucd_mem(parsed):
    return [("", {})] if parsed else []


def check_ucd_mem(item, params, parsed):

    if not parsed:
        return

    # general errors
    error = parsed['error']
    if error and error != 'swap':
        yield 1, 'Error: %s' % error

    # map legacy levels
    if params.get('levels') is not None:
        params['levels_ram'] = params.pop('levels')

    results = check_memory_dict(parsed, params)
    for state, infotext, perfdata in results.values():
        yield state, infotext, perfdata

    # swap errors
    if 'error_swap' in parsed:
        if parsed['error_swap'] != 0 and parsed['error_swap_msg']:
            yield params.get("swap_errors", 0), 'Swap error: %s' % parsed['error_swap_msg']


# This check plugin uses the migrated section in cmk/base/plugins/agent_based/ucd_mem.py!
check_info['ucd_mem'] = {
    'parse_function': parse_ucd_mem,
    'inventory_function': inventory_ucd_mem,
    'check_function': check_ucd_mem,
    'service_description': 'Memory',
    'has_perfdata': True,
    'snmp_info': (
        ".1.3.6.1.4.1.2021.4",
        [
            "5",  # memTotalReal
            "6",  # memAvailReal
            "3",  # memTotalSwap
            "4",  # memAvailSwap
            "11",  # MemTotalFree
            "12",  # memMinimumSwap
            "13",  # memShared
            "14",  # memBuffer
            "15",  # memCached
            "100",  # memSwapError
            "2",  # memErrorName
            "101",  # smemSwapErrorMsg
        ]),

    # Some devices are reporting wrong data on
    # HOST-RESOURCES-MIB. Use UCD-MIB in these
    # cases instead
    'snmp_scan_function': is_ucd_mem,
    'default_levels_variable': 'ucd_mem_default_levels',
    'group': 'memory_simple',
}
