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

# WARNING: This check is deprecated and will be removed soon. Please
# update your agent and use lnx_if instead.

linux_nic_check = "lnx_if"


def inventory_netif_link(info):
    if linux_nic_check != "legacy":
        return []
    return [(i[0], i[4] == "yes", i[4] == "yes") for i in info if len(i) == 5]


def check_netif_link(item, targetstate, info):
    links = [i[4] for i in info if i[0] == item]
    if len(links) == 0:
        return (2, "unknown network device")
    elif len(links) != 1:
        return (3, "network devices listed more than once")
    if links[0] == "yes":
        link = True
    elif links[0] == "no":
        link = False
    else:
        return (3, "invalid link state '%s'" % link)

    if link == targetstate:
        if link:
            return (0, "Link is up")
        return (0, "no link / NIC unused")

    if link:
        return (1, "Link is up, NIC should be unused")
    return (2, "no link")


def inventory_netif_params(info):
    if linux_nic_check != "legacy":
        return []
    return [(i[0], "", tuple(i[1:4])) for i in info if len(i) == 5]


def check_netif_params(item, params, info):
    infolist = [i[1:4] for i in info if i[0] == item]
    if len(infolist) == 0:
        return (2, "unknown network device")
    elif len(infolist) != 1:
        return (3, "network devices listed more than once")
    act_params = tuple(infolist[0])
    if act_params == params:
        return (0, "%s" % (",".join(act_params),))
    return (2, "%s (should be %s)" % (",".join(act_params), ",".join(params)))


check_info["netif.params"] = {
    "check_function": check_netif_params,
    "inventory_function": inventory_netif_params,
    "service_description": "NIC %s parameter",
}

check_info["netif.link"] = {
    "check_function": check_netif_link,
    "inventory_function": inventory_netif_link,
    "service_description": "NIC %s link",
}
