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


def inv_lnx_if(parsed, params, inventory_tree):
    inv_lnx_if_ports(parsed[0], params, inventory_tree)
    inv_lnx_if_addresses(parsed[1], inventory_tree)


# TODO unify with other if inventory plugins
def inv_lnx_if_ports(parsed, params, inventory_tree):
    usage_port_types = params.get(
        "usage_port_types",
        ['6', '32', '62', '117', '127', '128', '129', '180', '181', '182', '205', '229'])

    def render_mac_address(bytestring):
        return ":".join(["%02s" % hex(ord(m))[2:] for m in bytestring]).replace(' ', '0').upper()

    interfaces = []
    total_ethernet_ports = 0
    available_ethernet_ports = 0
    for interface in parsed:

        if interface.descr.startswith("veth"):
            # Always exclude dockers veth* interfaces on docker nodes
            continue

        if interface.type in ("231", "232"):
            continue  # Useless entries for "TenGigabitEthernet2/1/21--Uncontrolled"
            # Ignore useless half-empty tables (e.g. Viprinet-Router)

        if_info = {
            "index": int(interface.index),
            "description": interface.descr,
            "alias": interface.alias,
            "speed": interface.speed,
            "phys_address": render_mac_address(interface.phys_address),
            "oper_status": int(interface.oper_status),
            "port_type": int(interface.type),
        }

        if interface.type in usage_port_types:
            if_available = interface.oper_status == '2'
            total_ethernet_ports += 1
            if if_available:
                available_ethernet_ports += 1
        else:
            if_available = None

        if_info["available"] = if_available
        interfaces.append(if_info)

    node = inventory_tree.get_list("networking.interfaces:")
    node.extend(sorted(interfaces, key=lambda r: r.get('index')))

    node = inventory_tree.get_dict("networking.")
    node["available_ethernet_ports"] = available_ethernet_ports
    node["total_ethernet_ports"] = total_ethernet_ports
    node["total_interfaces"] = len(parsed)


def inv_lnx_if_addresses(parsed, inventory_tree):
    def parse_address(device, network, ty):
        address = network.split("/")[0]
        return {
            "device": device,
            "address": address,
            "type": ty,
        }

    addresses = inventory_tree.get_list("networking.addresses:")
    for if_name, attrs in parsed.items():
        for entry in attrs.get("inet", {}):
            addresses.append(parse_address(if_name, entry, "ipv4"))
        for entry in attrs.get("inet6", {}):
            addresses.append(parse_address(if_name, entry, "ipv6"))


inv_info['lnx_if'] = {
    'inv_function': inv_lnx_if,
}
