#!/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 inventory_brocade_info(info):
    data = "".join(brocade_info_try_it(info))
    if data != "----":
        return [(None, None)]


def brocade_info_try_it(info):
    try:
        model = info[0][0][0]
    except Exception:
        model = "-"
    try:
        wwn = info[2][0][0]
        wwn = " ".join(["%02X" % ord(tok) for tok in wwn])
    except Exception:
        wwn = "-"
    try:
        fw = info[1][0][0]
    except Exception:
        fw = "-"
    try:
        ssn = info[1][0][1]
    except Exception:
        ssn = "-"

    return model, ssn, fw, wwn


def brocade_info_parse_wwn(val):
    if val == "":
        val = "-"
    elif val != "-":
        val = ":".join(val.split(" ")[:8])
    return val


def check_brocade_info(item, params, info):
    model, ssn, fw, wwn = brocade_info_try_it(info)
    data = "".join((model, ssn, fw, wwn))
    if data != "----":
        wwn = brocade_info_parse_wwn(wwn)
        infotext = "Model: %s, SSN: %s, Firmware Version: %s, WWN: %s" % (model, ssn, fw, wwn)
        return 0, infotext
    return 3, "no information found"


def scan_brocade_info(oid):
    return (oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.4.1.1588") or
            oid(".1.3.6.1.2.1.1.2.0").startswith(".1.3.6.1.24.1.1588.2.1.1")
            # Extreme SLX9640; SLX Operating System Version 20.1.X:
            or oid(".1.3.6.1.2.1.1.2.0")
            == ".1.3.6.1.4.1.1916.2.306") and oid(".1.3.6.1.4.1.1588.2.1.1.1.1.6.0") is not None


check_info["brocade_info"] = {
    'check_function': check_brocade_info,
    'inventory_function': inventory_brocade_info,
    'service_description': 'Brocade Info',
    'snmp_info': [
        (
            ".1.3.6.1.2.1.47.1.1.1.1.2",
            [
                1,  # entPhysicalDescr.1
            ],
        ),
        (
            ".1.3.6.1.4.1.1588.2.1.1.1.1",
            [
                6,  # swFirmwareVersion
                10,  # swSsn
            ]),
        (
            ".1.3.6.1.3.94.1.6.1",
            [
                1,  # connUnitId
            ],
        ),
    ],
    'snmp_scan_function': scan_brocade_info,
}
