#!/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.filerdisks import *  # pylint: disable=wildcard-import,unused-wildcard-import
# Agent output:
# <<<netapp_api_disk:sep(9)>>>

factory_settings['filer_disks_default_levels'] = FILER_DISKS_CHECK_DEFAULT_PARAMETERS


def inventory_netapp_api_disk_summary(info):
    return [(None, {})]


def check_netapp_api_disk_summary(_no_item, params, info):
    disks_info = {}
    for line in info:
        disk_uid = line[0].split()[1]
        disks_info.setdefault(disk_uid, {})
        for entry in line[1:]:
            tokens = entry.split(" ", 1)
            disks_info[disk_uid][tokens[0]] = tokens[1]

    # Convert legacy levels
    if "broken_spare_ratio" in params:
        params = {"failed_spare_ratio": params["broken_spare_ratio"]}

    disks = disks_info

    # The device can contain disks who belongs to another filer. We only check the ones
    # belonging to this filer.
    # TODO Do we need that?
    my_disks = dict(
        [disk for disk in disks.items() if not disk[1].get("raid-state") in ["remote", "partner"]])

    disks_converted = []
    for disk in my_disks.values():
        # Collection the disk identity
        disk_info = "Serial: %s" % disk.get("serial-number")
        if "physical-space" in disk:
            disk_info += ", Size: %s" % get_bytes_human_readable(int(disk["physical-space"]))
            disk['capacity'] = int(disk['physical-space'])

        disk['identifier'] = disk_info
        disk['type'] = False
        raid_type = disk.get("raid-type")
        raid_state = disk.get("raid-state")
        if raid_state == "broken":
            disk['state'] = 'failed'
        elif disk.get("prefailed", "false") not in ["false", "None"]:
            disk['state'] = 'prefailed'
        elif raid_state == "spare":
            disk['state'] = "spare"
        else:
            disk['state'] = 'ok'

        if raid_type in ["parity", "dparity"]:
            disk['type'] = 'parity'
        elif raid_type == "data":
            disk['type'] = 'data'

        disks_converted.append(disk)

    return check_filer_disks(disks_converted, params)


check_info["netapp_api_disk.summary"] = {
    'check_function': check_netapp_api_disk_summary,
    'inventory_function': inventory_netapp_api_disk_summary,
    'service_description': 'NetApp Disks Summary',
    'group': 'netapp_disks',
    'has_perfdata': True,
    'default_levels_variable': 'filer_disks_default_levels',
}
