#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2015             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.

# <<<citrix_controller>>>
# ControllerState Active
# ControllerVersion 7.6.0.5024
# DesktopsRegistered 29
# LicensingServerState OK
# LicensingGraceState NotActive
# ActiveSiteServices RZ2XenPool01 - Cisco UCS VMware
# TotalFarmActiveSessions 262
# TotalFarmInactiveSessions 14

#   .--Active Site Services------------------------------------------------.
#   |               _        _   _             ____  _ _                   |
#   |              / \   ___| |_(_)_   _____  / ___|(_) |_ ___             |
#   |             / _ \ / __| __| \ \ / / _ \ \___ \| | __/ _ \            |
#   |            / ___ \ (__| |_| |\ V /  __/  ___) | | ||  __/            |
#   |           /_/   \_\___|\__|_| \_/ \___| |____/|_|\__\___|            |
#   |                                                                      |
#   |                ____                  _                               |
#   |               / ___|  ___ _ ____   _(_) ___ ___  ___                 |
#   |               \___ \ / _ \ '__\ \ / / |/ __/ _ \/ __|                |
#   |                ___) |  __/ |   \ V /| | (_|  __/\__ \                |
#   |               |____/ \___|_|    \_/ |_|\___\___||___/                |
#   |                                                                      |
#   '----------------------------------------------------------------------'


def inventory_citrix_controller_services(info):
    for line in info:
        if line[0] == "ActiveSiteServices":
            return [(None, None)]


def check_citrix_controller_services(_no_item, _no_params, info):
    for line in info:
        if line[0] == "ActiveSiteServices":
            return 0, " ".join(line[1:])


check_info["citrix_controller.services"] = {
    "inventory_function": inventory_citrix_controller_services,
    "check_function": check_citrix_controller_services,
    "service_description": "Citrix Active Site Services",
}

#.
#   .--Desktops Registered-------------------------------------------------.
#   |               ____            _    _                                 |
#   |              |  _ \  ___  ___| | _| |_ ___  _ __  ___                |
#   |              | | | |/ _ \/ __| |/ / __/ _ \| '_ \/ __|               |
#   |              | |_| |  __/\__ \   <| || (_) | |_) \__ \               |
#   |              |____/ \___||___/_|\_\\__\___/| .__/|___/               |
#   |                                            |_|                       |
#   |            ____            _     _                    _              |
#   |           |  _ \ ___  __ _(_)___| |_ ___ _ __ ___  __| |             |
#   |           | |_) / _ \/ _` | / __| __/ _ \ '__/ _ \/ _` |             |
#   |           |  _ <  __/ (_| | \__ \ ||  __/ | |  __/ (_| |             |
#   |           |_| \_\___|\__, |_|___/\__\___|_|  \___|\__,_|             |
#   |                      |___/                                           |
#   '----------------------------------------------------------------------'


def inventory_citrix_controller_registered(info):
    for line in info:
        if line[0] == "DesktopsRegistered":
            return [(None, None)]


def check_citrix_controller_registered(_no_item, _no_params, info):
    for line in info:
        if line[0] == "DesktopsRegistered":
            try:
                count_desktops = int(line[1])
            except (IndexError, ValueError):
                # Is UNKNOWN right behaviour?
                return 3, 'No desktops registered'
            return 0, "%d" % count_desktops, [("registered_desktops", count_desktops)]


check_info["citrix_controller.registered"] = {
    "inventory_function": inventory_citrix_controller_registered,
    "check_function": check_citrix_controller_registered,
    "service_description": "Citrix Desktops Registered",
    "has_perfdata": True,
}

#.
#   .--Total Sessions------------------------------------------------------.
#   |    _____     _        _   ____                _                      |
#   |   |_   _|__ | |_ __ _| | / ___|  ___  ___ ___(_) ___  _ __  ___      |
#   |     | |/ _ \| __/ _` | | \___ \ / _ \/ __/ __| |/ _ \| '_ \/ __|     |
#   |     | | (_) | || (_| | |  ___) |  __/\__ \__ \ | (_) | | | \__ \     |
#   |     |_|\___/ \__\__,_|_| |____/ \___||___/___/_|\___/|_| |_|___/     |
#   |                                                                      |
#   '----------------------------------------------------------------------'


def inventory_citrix_controller_sessions(info):
    inv = False
    for line in info:
        inv = inv or ("sessions" in line[0].lower())

    if inv:
        return [(None, {})]
    return []


def check_citrix_controller_sessions(_no_item, params, info):
    if params is None:
        params = {}

    session = {
        "active": 0,
        "inactive": 0,
    }
    for line in info:
        if line[0] == "TotalFarmActiveSessions":
            session["active"] = int(line[1])
        elif line[0] == "TotalFarmInactiveSessions":
            session["inactive"] = int(line[1])

    session["total"] = session["active"] + session["inactive"]

    state = 0
    messages = []
    perf = []
    for what in ['total', 'active', 'inactive']:
        warn, crit = params.get(what, (None, None))
        perf.append((what + "_sessions", session[what], warn, crit))
        if crit is not None and session[what] >= crit:
            messages.append("%s: %s(!!)" % (what, session[what]))
            state = 2
        elif warn is not None and session[what] >= warn:
            messages.append("%s: %s(!)" % (what, session[what]))
            state = max(state, 1)
        else:
            messages.append("%s: %s" % (what, session[what]))

    return state, ", ".join(messages), perf


check_info["citrix_controller.sessions"] = {
    "inventory_function": inventory_citrix_controller_sessions,
    "check_function": check_citrix_controller_sessions,
    "service_description": "Citrix Total Sessions",
    "has_perfdata": True,
    "group": "citrix_sessions",
}

#.
#   .--Licensing State-----------------------------------------------------.
#   |  _     _                    _               ____  _        _         |
#   | | |   (_) ___ ___ _ __  ___(_)_ __   __ _  / ___|| |_ __ _| |_ ___   |
#   | | |   | |/ __/ _ \ '_ \/ __| | '_ \ / _` | \___ \| __/ _` | __/ _ \  |
#   | | |___| | (_|  __/ | | \__ \ | | | | (_| |  ___) | || (_| | ||  __/  |
#   | |_____|_|\___\___|_| |_|___/_|_| |_|\__, | |____/ \__\__,_|\__\___|  |
#   |                                     |___/                            |
#   '----------------------------------------------------------------------'


def inventory_citrix_controller_licensing(info):
    if info:
        return [(None, None)]


def check_citrix_controller_licensing(_no_item, _no_params, info):

    statedict = {
        "licensingserverstate": ("Licensing Server State", {
            "ServerNotSpecified": (2, "server not specified"),
            "NotConnected": (1, "not connected"),
            "OK": (0, "OK"),
            "LicenseNotInstalled": (2, "license not installed"),
            "LicenseExpired": (2, "licenese expired"),
            "Incompatible": (2, "incompatible"),
            "Failed": (2, "failed"),
        }),
        "licensinggracestate": ("Licensing Grace State", {
            "NotActive": (0, "not active"),
            "Active": (2, "active"),
            "InOutOfBoxGracePeriod": (1, "in-out-of-box grace period"),
            "InSupplementalGracePeriod": (1, "in-supplemental grace period"),
            "InEmergencyGracePeriod": (2, "in-emergency grace period"),
            "GracePeriodExpired": (2, "grace period expired"),
            "Expired": (2, "expired"),
        }),
    }
    # piggy back data might deliver double data
    detected_states = []
    for line in info:
        if line[0].lower() in statedict and line[0] not in detected_states:
            detected_states.append(line[0])
            title, states = statedict[line[0].lower()]
            try:
                raw_state = line[1]
            except IndexError:
                continue
            state, state_readable = states.get(raw_state, (3, 'unknown[%s]' % raw_state))
            yield state, "%s: %s" % (title, state_readable)


check_info["citrix_controller.licensing"] = {
    "inventory_function": inventory_citrix_controller_licensing,
    "check_function": check_citrix_controller_licensing,
    "service_description": "Citrix Controller Licensing",
}

#.
#   .--Controller State----------------------------------------------------.
#   |             ____            _             _ _                        |
#   |            / ___|___  _ __ | |_ _ __ ___ | | | ___ _ __              |
#   |           | |   / _ \| '_ \| __| '__/ _ \| | |/ _ \ '__|             |
#   |           | |__| (_) | | | | |_| | | (_) | | |  __/ |                |
#   |            \____\___/|_| |_|\__|_|  \___/|_|_|\___|_|                |
#   |                                                                      |
#   |                       ____  _        _                               |
#   |                      / ___|| |_ __ _| |_ ___                         |
#   |                      \___ \| __/ _` | __/ _ \                        |
#   |                       ___) | || (_| | ||  __/                        |
#   |                      |____/ \__\__,_|\__\___|                        |
#   |                                                                      |
#   '----------------------------------------------------------------------'


def inventory_citrix_controller(info):
    for line in info:
        if line[0] == "ControllerState":
            return [(None, None)]


def check_citrix_controller(_no_item, _no_params, info):
    for line in info:
        if line[0] == "ControllerState":
            state = 0
            try:
                raw_state = line[1]
            except IndexError:
                return 3, 'unknown'
            if raw_state != "Active":
                state = 2
            return state, raw_state


check_info["citrix_controller"] = {
    "inventory_function": inventory_citrix_controller,
    "check_function": check_citrix_controller,
    "service_description": "Citrix Controller State",
}
