#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# <<<lnx_bonding:sep(58)>>>
# ==> bond0 <==
# Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)
#
# Bonding Mode: load balancing (round-robin)
# MII Status: down
# MII Polling Interval (ms): 0
# Up Delay (ms): 0
# Down Delay (ms): 0
#
# ==> bond1 <==
# Ethernet Channel Bonding Driver: v3.2.5 (March 21, 2008)
#
# Bonding Mode: fault-tolerance (active-backup)
# Primary Slave: eth0
# Currently Active Slave: eth0
# MII Status: up
# MII Polling Interval (ms): 100
# Up Delay (ms): 0
# Down Delay (ms): 0
#
# Slave Interface: eth4
# MII Status: up
# Link Failure Count: 0
# Permanent HW addr: 00:1b:21:49:d4:e4
#
# Slave Interface: eth0
# MII Status: up
# Link Failure Count: 1
# Permanent HW addr: 00:26:b9:7d:89:2e

def parse_lnx_bonding(info):
    def strip_popd_garbage(info):
        for line in info:
            if len(line) != 1 or not line[0].startswith("/"):
                yield line

    lines = strip_popd_garbage(info)
    bonds = {}

    # Skip header with bonding version
    try:
        bond = lines.next()[0].split()[1]
        bonds[bond] = {}
        while True:
            # ==> bond0 <==
            lines.next() # Skip Channel Bonding Driver

            # Parse global part
            main = {}
            bonds[bond]["main"] = main
            while True:
                line = lines.next()
                main[line[0].strip()] = line[1].strip()
                if line[0].strip() == "Down Delay (ms)":
                    break

            # Here could come an additional part:
            # "802.3ad info". We detect the end of
            # this part by finding th efirst "Slave Interface"
            eth = None

            # Parse interfaces
            interfaces = {}
            bonds[bond]["interfaces"] = interfaces
            while True:
                line = lines.next()
                if line[0].startswith("==>"):
                    bond = line[0].split()[1]
                    bonds[bond] = {}
                    break
                elif line[0].strip() == "Slave Interface":
                    eth = line[1].strip()
                    interfaces[eth] = {}
                elif line and eth:
                    interfaces[eth][line[0].strip()] = ":".join(line[1:]).strip()

    except StopIteration:
        pass

    # Now convert to generic dict, also used by other bonding checks
    converted = {}
    for bond, status in bonds.items():
        interfaces = {}
        for eth, ethstatus in status["interfaces"].items():
            interfaces[eth] = {
                "status"   : ethstatus["MII Status"],
                "hwaddr"   : ethstatus.get("Permanent HW addr", ""),
                "failures" : int(ethstatus["Link Failure Count"]),
            }
        converted[bond] = {
            "status"      : status["main"]["MII Status"],
            "mode"        : status["main"]["Bonding Mode"].split('(')[0].strip(),
            "interfaces"  : interfaces,
        }
        if "Currently Active Slave" in status["main"]:
            converted[bond]["active"] = status["main"]["Currently Active Slave"]
        if "Primary Slave" in status["main"]:
            converted[bond]["primary"] = status["main"]["Primary Slave"].split()[0]
    return converted



check_info['lnx_bonding'] = {
    "check_function"          : lambda item,params,info: check_bonding(item, params, parse_lnx_bonding(info)),
    "inventory_function"      : lambda info: inventory_bonding(parse_lnx_bonding(info)),
    "service_description"     : "Bonding Interface %s",
    "group"                   : "bonding",
    "includes"                : [ "bonding.include" ],
}
