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

# .1.3.6.1.4.1.3375.2.1.2.4.4.3.1.1.  index for ifname
# .1.3.6.1.4.1.3375.2.1.2.4.1.2.1.17. index for ifstate
# .1.3.6.1.4.1.3375.2.1.2.4.4.3.1.3.  index for IN bytes
# .1.3.6.1.4.1.3375.2.1.2.4.4.3.1.5.  index for OUT bytes

f5_bigip_interface_states = {
    1: "down (has no link and is initialized)",
    2: "disabled (has been forced down)",
    3: "uninitialized (has not been initialized)",
    4: "loopback (in loopback mode)",
    5: "unpopulated (interface not physically populated)",
}


def check_f5_bigip_interfaces(item, params, info):
    for port, ifstate, inbytes, outbytes in info:
        if item != port:
            continue

        if int(ifstate) != 0:
            return (
                2,
                "State of %s is %s"
                % (f5_bigip_interface_states.get(ifstate, "unhandled (%d)" % ifstate), port),
            )

        this_time = int(time.time())
        in_per_sec = get_rate("f5_interface.in.%s" % item, this_time, saveint(inbytes))
        out_per_sec = get_rate("f5_interface.out.%s" % item, this_time, saveint(outbytes))

        inbytes_h = get_bytes_human_readable(in_per_sec)
        outbytes_h = get_bytes_human_readable(out_per_sec)
        perf = [
            ("bytes_in", in_per_sec),
            ("bytes_out", out_per_sec),
        ]
        return (0, "in bytes: %s/s, out bytes: %s/s" % (inbytes_h, outbytes_h), perf)
    return 3, "Interface not found in SNMP data"


check_info["f5_bigip_interfaces"] = {
    "check_function": check_f5_bigip_interfaces,
    "inventory_function": lambda info: [(x[0], {"state": 0}) for x in info if int(x[1]) == 0],
    "service_description": "f5 Interface %s",
    "has_perfdata": True,
    "snmp_scan_function": lambda oid: oid(".1.3.6.1.2.1.1.2.0")
    in [".1.3.6.1.4.1.3375.2.1.3.4.10", ".1.3.6.1.4.1.3375.2.1.3.4.20"],
    "snmp_info": (".1.3.6.1.4.1.3375.2.1.2.4", ["4.3.1.1", "1.2.1.17", "4.3.1.3", "4.3.1.5"]),
}
