#!/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.ibm_svc import *  # pylint: disable=wildcard-import,unused-wildcard-import
# Example output from agent:
# <<<ibm_svc_host:sep(58)>>>
# 0:h_esx01:2:4:degraded
# 1:host206:2:2:online
# 2:host105:2:2:online
# 3:host106:2:2:online


def parse_ibm_svc_host(info):
    dflt_header = [
        u'id',
        u'name',
        u'port_count',
        u'iogrp_count',
        u'status',
        u'site_id',
        u'site_name',
        u'host_cluster_id',
        u'host_cluster_name',
    ]
    return parse_ibm_svc_with_header(info, dflt_header)


def check_ibm_svc_host(item, params, parsed):
    if params is None:
        # Old inventory rule until version 1.2.7
        # params were None instead of empty dictionary
        params = {'always_ok': False}

    degraded = 0
    offline = 0
    active = 0
    inactive = 0
    other = 0
    for rows in parsed.values():
        for data in rows:
            status = data['status']
            if status == 'degraded':
                degraded += 1
            elif status == 'offline':
                offline += 1
            elif status in ['active', 'online']:
                active += 1
            elif status == 'inactive':
                inactive += 1
            else:
                other += 1

    if 'always_ok' in params:
        # Old configuration rule
        # This was used with only one parameter always_ok until version 1.2.7
        perfdata = [
            ("active", active),
            ("inactive", inactive),
            ("degraded", degraded),
            ("offline", offline),
            ("other", other),
        ]
        yield 0, "%s active, %s inactive" % (active, inactive), perfdata

        if degraded > 0:
            yield (not params['always_ok'] and 1 or 0), "%s degraded" % degraded
        if offline > 0:
            yield (not params['always_ok'] and 2 or 0), "%s offline" % offline
        if other > 0:
            yield (not params['always_ok'] and 1 or 0), "%s in an unidentified state" % other
    else:
        warn, crit = params.get('active_hosts', (None, None))

        if crit is not None and active <= crit:
            yield 2, "%s active" % active
        elif warn is not None and active <= warn:
            yield 1, "%s active" % active
        else:
            yield 0, "%s active" % active

        for ident, value in [
            ('inactive', inactive),
            ('degraded', degraded),
            ('offline', offline),
            ('other', other),
        ]:
            warn, crit = params.get(ident + '_hosts', (None, None))

            if crit is not None and value >= crit:
                state = 2
            if warn is not None and value >= warn:
                state = 1
            else:
                state = 0
            yield state, "%s %s" % (value, ident), [(ident, value, warn, crit)]


check_info["ibm_svc_host"] = {
    "parse_function": parse_ibm_svc_host,
    "check_function": check_ibm_svc_host,
    "inventory_function": discover_single,
    "service_description": "Hosts",
    "has_perfdata": True,
    "group": "ibm_svc_host",
}
