#!/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.df import *  # pylint: disable=wildcard-import,unused-wildcard-import

# 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.size_trend import *  # pylint: disable=wildcard-import,unused-wildcard-import
from cmk.base.plugins.agent_based.utils.df import df_discovery

# NAME    SIZE  ALLOC   FREE  CAP  HEALTH  ALTROOT
# app02  39.8G  14.1G  25.6G  35%  ONLINE  -
# rpool  39.8G  32.9G  6.81G  82%  ONLINE  -

# Or also:
# NAME        SIZE   USED  AVAIL    CAP  HEALTH  ALTROOT
# sth_ds      278G   127G   151G    45%  ONLINE  -


def parse_zpool(info):
    def canonize_header_entry(entry):
        if entry == "used":
            return "alloc"
        elif entry == "avail":
            return "free"
        return entry

    result = {}
    if len(info) == 0:
        return result

    header = [canonize_header_entry(item.lower()) for item in info[0]]
    for line in info[1:]:
        result[line[0]] = dict(zip(header, line))
    return result


def inventory_zpool(parsed):
    return df_discovery(host_extra_conf(host_name(), filesystem_groups), list(parsed))


def check_zpool(item, params, parsed):
    def mb(val):
        idx = None
        # split number from unit
        for idx, ch in enumerate(val):
            if ch not in "0123456789.-":
                break
        num = float(val[:idx])
        unit = val[idx:].lstrip().lower()
        unit = ["b", "k", "m", "g", "t", "p"].index(unit)

        return num * (1024 ** (unit - 2))

    fslist = []
    for pool, entry in parsed.items():
        if "patterns" in params or item == pool:
            fslist.append((pool, mb(entry["size"]), mb(entry["free"]), 0))

    return df_check_filesystem_list(item, params, fslist)


check_info["zpool"] = {
    "check_function": check_zpool,
    "inventory_function": inventory_zpool,
    "parse_function": parse_zpool,
    "service_description": "Storage Pool %s",
    "has_perfdata": True,
    "group": "filesystem",
}
