#!/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 plugin:
# <<<citrix_licenses>>>
# PVS_STD_CCS 80 0
# PVS_STD_CCS 22 0
# CEHV_ENT_CCS 22 0
# MPS_ENT_CCU 2160 1636
# MPS_ENT_CCU 22 22
# XDT_ENT_UD 22 18
# XDS_ENT_CCS 22 0
# PVSD_STD_CCS 42 0


def parse_citrix_licenses(info):
    parsed = {}
    for line in info:
        try:
            have = int(line[1])
            used = int(line[2])
        except (IndexError, ValueError):
            continue
        license_type = line[0]
        licenses = parsed.setdefault(license_type, (0, 0))
        parsed[license_type] = (licenses[0] + have, licenses[1] + used)
    return parsed


def inventory_citrix_licenses(parsed):
    return [(license_type, None) for license_type in parsed]


@get_parsed_item_data
def check_citrix_licenses(item, params, data):
    have, used = data
    if not have:
        return 3, "No licenses of that type found"
    return license_check_levels(have, used, params)


check_info["citrix_licenses"] = {
    "parse_function": parse_citrix_licenses,
    "check_function": check_citrix_licenses,
    "inventory_function": inventory_citrix_licenses,
    "service_description": "Citrix Licenses %s",
    "has_perfdata": True,
    "group": "citrix_licenses",
}
