#!/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_util 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

#    UCD-SNMP-MIB::ssCpuRawUser.0 = Counter32: 219998591
#    UCD-SNMP-MIB::ssCpuRawNice.0 = Counter32: 0
#    UCD-SNMP-MIB::ssCpuRawSystem.0 = Counter32: 98206536
#    UCD-SNMP-MIB::ssCpuRawIdle.0 = Counter32: 3896034232
#    UCD-SNMP-MIB::ssCpuRawWait.0 = Counter32: 325152257
#    UCD-SNMP-MIB::ssCpuRawInterrupt.0 = Counter32: 1940759
#    UCD-SNMP-MIB::ssIORawSent.0 = Counter32: 898622850
#    UCD-SNMP-MIB::ssIORawReceived.0 = Counter32: 445747508
#    UCD-SNMP-MIB::ssCpuRawSoftIRQ.0 = Counter32: 277402

# Although this variable is no longer used we keep it for backwards
# compatibility so that old configs in automation calls autocheck do not
# crash.
kernel_util_default_levels = None


def parse_ucd_cpu_util(info):
    if not info:
        return {}

    (
        error,
        raw_cpu_user,
        raw_cpu_nice,
        raw_cpu_system,
        raw_cpu_idle,
        raw_cpu_wait,
        raw_cpu_interrupt,
        raw_io_send,
        raw_io_received,
        raw_cpu_softirq,
    ) = info[0]

    raw_cpu_ticks = [
        raw_cpu_user or None,
        raw_cpu_nice or None,
        raw_cpu_system or None,
        raw_cpu_idle or None,
        raw_cpu_wait or None,
        raw_cpu_interrupt or None,
        raw_cpu_softirq or None,
    ]

    try:
        return {
            "error": error or None,
            "cpu_ticks": CPUInfo("cpu", *raw_cpu_ticks),
            "raw_io_send": raw_io_send,
            "raw_io_received": raw_io_received,
        }
    except ValueError:
        return


def inventory_ucd_cpu_util(info):
    if info:
        yield None, {}


def check_ucd_cpu_util(item, params, parsed):
    now = time.time()
    error = parsed["error"]
    if error is not None and error != "systemStats":
        yield 1, "Error: %s" % error

    cpu_ticks = parsed["cpu_ticks"]
    for result in check_cpu_util_unix(cpu_ticks, params):
        yield result

    try:
        raw_io_received = int(parsed["raw_io_received"])
        raw_io_send = int(parsed["raw_io_send"])
    except ValueError:
        return

    perfdata = [
        ("read_blocks", get_rate("io_received", now, raw_io_received), None, None),
        ("write_blocks", get_rate("io_send", now, raw_io_send), None, None),
    ]
    yield 0, "", perfdata


check_info["ucd_cpu_util"] = {
    "parse_function": parse_ucd_cpu_util,
    "inventory_function": inventory_ucd_cpu_util,
    "check_function": check_ucd_cpu_util,
    "service_description": "CPU utilization",
    "has_perfdata": True,
    "snmp_info": (
        ".1.3.6.1.4.1.2021.11",
        [
            "2",  # ssErrorName
            "50",  # ssCpuRawUser
            "51",  # ssCpuRawNice
            "52",  # ssCpuRawSystem
            "53",  # ssCpuRawIdle
            "54",  # ssCpuRawWait
            "56",  # ssCpuRawInterrupt
            "57",  # ssIORawSent
            "58",  # ssIORawReceived
            "61",  # ssCpuRawSoftIRQ
        ],
    ),
    "snmp_scan_function": prefer_hr_else_ucd,
    "group": "cpu_iowait",
}
