#!/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.stormshield import *  # pylint: disable=wildcard-import,unused-wildcard-import

# Unfortunalty we can not use the normal interface names here, because
# the interface IDs from the enterprise MIBs and RFC are not the same.
# We decided using the interface description for inventory (best practise)


def inventory_stormshield_packets(info):
    for descrip, _name, iftype, _pktaccepted, _pktblocked, _pkticmp, _tcp, _udp in info:
        if iftype.lower() in ["ethernet", "ipsec"]:
            yield descrip, {}


def check_stormshield_packets(item, params, info):
    for descrip, name, _iftype, pktaccepted, pktblocked, pkticmp, tcp, udp in info:
        if item == descrip:
            now = time.time()
            rate_pktaccepted = get_rate("acc_%s" % item, now, int(pktaccepted))
            rate_pktblocked = get_rate("block_%s" % item, now, int(pktblocked))
            rate_pkticmp = get_rate("icmp_%s" % item, now, int(pkticmp))
            infotext = "[%s], tcp: %s, udp: %s" % (name, tcp, udp)
            perfdata = [
                ("tcp_active_sessions", tcp),
                ("udp_active_sessions", udp),
                ("packages_accepted", rate_pktaccepted),
                ("packages_blocked", rate_pktblocked),
                ("packages_icmp_total", rate_pkticmp),
            ]
            yield 0, infotext, perfdata


check_info["stormshield_packets"] = {
    "inventory_function": inventory_stormshield_packets,
    "check_function": check_stormshield_packets,
    "default_levels_variable": "stormshield_packets_default_levels",
    "service_description": "Packet Stats %s",
    "has_perfdata": True,
    "snmp_info": (
        ".1.3.6.1.4.1.11256.1.4.1.1",
        [
            "2",  # Description
            "3",  # Name
            "6",  # IfType
            "11",  # PktAccepted
            "12",  # PktBlocked
            "16",  # PktIcmp
            "23",  # TcpConnCount
            "24",  # UdpConnCount
        ],
    ),
    "snmp_scan_function": stormshield_scan_function,
}
