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

# Example output from agent:
# esx_vsphere_licenses:sep(9)>>>
# VMware vSphere 5 Standard   100 130
# VMware vSphere 5 Enterprise 86 114
# VMware vSphere 5 Enterprise 22 44 # Licenses may appear multiple times (keys different)
# vCenter Server 5 Standard   1 1


def parse_esx_vsphere_licenses(info):
    parsed = {}
    for line in info:
        name, values = line
        parsed.setdefault(name, {"used": 0, "total": 0, "keys": 0})
        used, total = values.split()
        parsed[name]["used"] += int(used)
        parsed[name]["total"] += int(total)
        parsed[name]["keys"] += 1
    return parsed


def inventory_esx_vsphere_licenses(parsed):
    return [(key, None) for key in parsed]


def check_esx_vsphere_licenses(item, params, parsed):
    license_ = parsed.get(item)
    if not license_:
        return 3, "License not found in agent output"

    status, infotext, perfdata = license_check_levels(license_["total"], license_["used"], params)
    infotext = "%s Key(s), " % license_["keys"] + infotext
    return status, infotext, perfdata


check_info["esx_vsphere_licenses"] = {
    "parse_function": parse_esx_vsphere_licenses,
    "inventory_function": inventory_esx_vsphere_licenses,
    "check_function": check_esx_vsphere_licenses,
    "service_description": "License %s",
    "has_perfdata": True,
    "group": "esx_licenses",
}
