#!/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.checkpoint 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.mem 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 item 'System' 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.

# comNET GmbH, Fabian Binder

# .1.3.6.1.4.1.2620.1.6.7.4.3.0 8101654528 --> CHECKPOINT-MIB::memTotalReal
# .1.3.6.1.4.1.2620.1.6.7.4.4.0 2091094016 --> CHECKPOINT-MIB::memAvailReal

factory_settings["checkpoint_memory_default_levels"] = {"levels": ("perc_used", (80.0, 90.0))}


def inventory_checkpoint_memory(info):
    if info and len(info[0]) > 1:
        return [("System", {})]


def check_checkpoint_memory(item, params, info):
    if isinstance(params, tuple):
        params = {"levels": ("perc_used", params)}

    mem_total_bytes, mem_used_bytes = map(int, info[0])
    return check_memory_element(
        "Usage",
        mem_used_bytes,
        mem_total_bytes,
        params.get("levels"),
        metric_name="memory_used",
    )


check_info["checkpoint_memory"] = {
    "inventory_function": inventory_checkpoint_memory,
    "check_function": check_checkpoint_memory,
    "service_description": "Memory",
    "has_perfdata": True,
    "snmp_info": (
        ".1.3.6.1.4.1.2620.1.6.7.4",
        [
            "3",  # memTotalReal64  -> Bytes
            "4",  # memActiveReal64 -> Bytes
        ],
    ),
    # Some devices are reporting wrong data on
    # HOST-RESOURCES-MIB. Use CHECKPOINT-MIB in these
    # cases instead
    "snmp_scan_function": scan_checkpoint,
    "default_levels_variable": "checkpoint_memory_default_levels",
    "group": "memory_simple",
}
