#!/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.cpu_load 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
# .1.3.6.1.4.1.2021.10.1.5.1 691        1  min
# .1.3.6.1.4.1.2021.10.1.5.2 855        5  min
# .1.3.6.1.4.1.2021.10.1.5.3 895        15 min
# .1.3.6.1.4.1.2021.10.1.6.1 1.350000   1  min
# .1.3.6.1.4.1.2021.10.1.6.2 1.250000   5  min
# .1.3.6.1.4.1.2021.10.1.6.3 1.240000   15 min

cpuload_default_levels = (5.0, 10.0)


def inventory_ucd_cpu_load(info):
    if len(info) == 3:
        return [(None, "cpuload_default_levels")]


def check_ucd_cpu_load(item, params, info):
    # Some devices provide only one table. We prefer float table
    this_cpu_load_table = []
    for int_cpu_load_str, float_cpu_load_str in info:
        if float_cpu_load_str:
            this_cpu_load_table.append(float(float_cpu_load_str.replace(",", ".")))
        elif int_cpu_load_str:
            this_cpu_load_table.append(float(int_cpu_load_str) / 100.0)
        else:
            this_cpu_load_table.append(0)

    # Note: Some dump devices send 12,540000 instead of 12.540000
    return check_cpu_load_generic(params, this_cpu_load_table)


check_info["ucd_cpu_load"] = {
    'inventory_function': inventory_ucd_cpu_load,
    'check_function': check_ucd_cpu_load,
    'service_description': 'CPU load',
    'has_perfdata': True,
    'snmp_info': (
        '.1.3.6.1.4.1.2021.10.1',
        [
            "5",  # UCD-SNMP-MIB::laLoadInt       Int table
            "6",  # UCD-SNMP-MIB::laLoadFloat     Float table
        ]),
    # 'CPU load' is not available in the HR-MIB
    # thus we cannot use 'prefer_hr_scan_function'
    'snmp_scan_function': is_ucd,
    'group': 'cpu_load',
}
