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

# Example output from agent:
# [zmucvm99-lds]
# accessible  True
# capacity    578478407680
# freeSpace   388398841856
# type    VMFS
# uncommitted 51973812224
# url /vmfs/volumes/513df1e9-12fd7366-ac5a-e41f13e69eaa


def parse_esx_vsphere_datastores(info):
    stores = {}
    for line in info:
        if line[0].startswith('['):
            name = line[0][1:-1]
            store = {}
            stores[name] = store
        else:
            # Seems that the url attribute can have an empty value
            if len(line) == 1:
                key = line[0].strip()
                value = None
            else:
                key, value = line

            if key == "accessible":
                value = value.lower() == "true"
            elif key in ["capacity", "freeSpace", "uncommitted"]:
                value = int(value)
            store[key] = value
    return stores


@get_parsed_item_data
def check_esx_vsphere_datastores(item, params, data):
    if not data["accessible"]:
        yield 2, "inaccessible"

    mib = 1024.0**2
    size_bytes = data.get("capacity")
    avail_bytes = data.get("freeSpace")
    if size_bytes is None or avail_bytes is None:
        return

    yield df_check_filesystem_single(  # pylint: disable=undefined-variable
        item, size_bytes / mib, avail_bytes / mib, 0, None, None, params)

    uncommitted_bytes = data.get("uncommitted")
    if uncommitted_bytes is None:
        return
    text_uncommitted = "Uncommitted: %s" % get_bytes_human_readable(uncommitted_bytes)
    yield 0, text_uncommitted, [('uncommitted', uncommitted_bytes / mib)]

    used_bytes = size_bytes - avail_bytes
    prov_bytes = used_bytes + uncommitted_bytes
    prov_percent = (prov_bytes * 100.) / size_bytes if size_bytes != 0 else 0

    warn, crit = params.get('provisioning_levels', (None, None))
    yield check_levels(prov_percent,
                       None, (warn, crit),
                       human_readable_func=get_percent_human_readable,
                       infoname="Provisioning")

    if warn is not None:
        # convert percent to abs MiB
        scale = size_bytes / mib / 100.
        yield 0, "", [('overprovisioned', prov_bytes / mib, scale * warn, scale * crit)]
    else:
        yield 0, "", [('overprovisioned', prov_bytes / mib)]


check_info['esx_vsphere_datastores'] = {
    "parse_function": parse_esx_vsphere_datastores,
    "inventory_function": discover(),
    "check_function": check_esx_vsphere_datastores,
    "service_description": "Filesystem %s",
    "includes": ['size_trend.include', 'df.include'],
    "has_perfdata": True,
    "group": "esx_vsphere_datastores",
    "default_levels_variable": "filesystem_default_levels",
}

#.
