#!/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.bonding import *  # pylint: disable=wildcard-import,unused-wildcard-import
# <<<ovs_bonding:sep(58)>>>
# [bond1]
# bond_mode: active-backup
# lacp: off
# bond-detect-mode: carrier
# updelay: 31000 ms
# downdelay: 200 ms
#
# slave eth5: enabled
#
# slave eth1: enabled
# active slave

factory_settings['bonding_default_levels'] = BONDING_CHECK_DEFAULT_PARAMETERS


def parse_ovs_bonding(info):
    bonds = {}
    for line in info:
        if line[0][0] == '[':
            bond = line[0][1:-1]
            bonds[bond] = {"active": None}
        elif len(line) == 2:
            left = line[0]
            right = line[1].strip()
            if left.startswith("slave"):
                bonds[bond].setdefault("interfaces", {})
                eth = left.split()[1]
                bonds[bond]["interfaces"][eth] = {
                    "status": right == "enabled" and "up" or right,
                }
                last_interface = eth
            else:
                bonds[bond][left] = right
        elif line[0] == 'active slave':
            bonds[bond]["active"] = last_interface

    parsed = {}
    for bond, status in bonds.items():
        all_down = True
        if not status['active']:
            continue
        for st in status["interfaces"].values():
            if st["status"] == "up":
                all_down = False
                break

        parsed[bond] = {
            "status": all_down and "down" or "up",
            "active": status["active"],
            "mode": status["bond_mode"],
            "interfaces": status["interfaces"],
        }

    return parsed


check_info['ovs_bonding'] = {
    "parse_function": parse_ovs_bonding,
    "check_function": check_bonding,
    "inventory_function": inventory_bonding,
    "service_description": "Bonding Interface %s",
    "default_levels_variable": "bonding_default_levels",
    "group": "bonding",
}
