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

from cmk.base.plugins.agent_based.utils import megaraid

factory_settings["storcli_vdrives_default_levels"] = megaraid.LDISKS_DEFAULTS


def parse_storcli_vdrives(info):

    parsed = {}

    controller_num = 0
    separator_count = 0
    for line in info:
        if line[0].startswith("-----"):
            separator_count += 1
        elif separator_count == 2:
            dg_vd, raid_type, rawstate, access, consistent = line[:5]
            parsed["C%i.%s" % (controller_num, dg_vd)] = {
                "raid_type": raid_type,
                "state": megaraid.expand_abbreviation(rawstate),
                "access": access,
                "consistent": consistent,
            }
        if separator_count == 3:
            # each controller has 3 separators, reset count and continue
            separator_count = 0
            controller_num += 1

    return parsed


def inventory_storcli_vdrives(parsed):
    for item in parsed:
        yield (item, {})


def check_storcli_vdrives(item, params, parsed):
    if item not in parsed:
        return

    yield 0, "Raid type is " + parsed[item]["raid_type"]
    yield 0, "Access: " + parsed[item]["access"]

    if parsed[item]["consistent"] == "Yes":
        yield 0, "Drive is consistent"
    else:
        yield 1, "Drive is not consistent"

    device_state = parsed[item]["state"]
    infotext = "State is %s" % device_state

    if device_state in params:
        status = params[device_state]
    else:
        status = 3
        infotext += " (unknown[%s])" % device_state
    yield status, infotext


check_info["storcli_vdrives"] = {
    "default_levels_variable": "storcli_vdrives_default_levels",
    "parse_function": parse_storcli_vdrives,
    "inventory_function": inventory_storcli_vdrives,
    "check_function": check_storcli_vdrives,
    "service_description": "RAID Virtual Drive %s",
    "group": "storcli_vdrives",
}
