#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk 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.

# <<<jenkins_instance>>>
# {"quietingDown": false, "nodeDescription": "the master Jenkins node",
# "numExecutors": 0, "mode": "NORMAL", "_class": "hudson.model.Hudson",
# "useSecurity": true}


import json

from cmk.base.check_api import LegacyCheckDefinition
from cmk.base.config import check_info

MAP_INSTANCE_STATE = {
    True: "yes",
    False: "no",
    "NORMAL": "normal",
    "EXCLUSIVE": "exclusive",
    None: "N/A",
}


def parse_jenkins_instance(string_table):
    parsed = {}

    for line in string_table:
        parsed.update(json.loads(line[0]))

    return parsed


def inventory_jenkins_instance(parsed):
    yield None, {}


def check_jenkins_instance(_no_item, _no_params, parsed):
    if not parsed:
        return

    inst_desc = parsed.get("nodeDescription")
    if inst_desc is not None:
        yield 0, "Description: %s" % inst_desc.title()

    for key, value, infotext in [
        ("quietingDown", False, "Quieting Down"),
        ("useSecurity", True, "Security used"),
    ]:
        state = 0
        parsed_data = parsed.get(key)

        if parsed_data is not None and parsed_data != value:
            state = 1
        elif parsed_data is None:
            state = 3

        yield state, f"{infotext}: {MAP_INSTANCE_STATE[parsed_data]}"


check_info["jenkins_instance"] = LegacyCheckDefinition(
    parse_function=parse_jenkins_instance,
    service_name="Jenkins Instance",
    discovery_function=inventory_jenkins_instance,
    check_function=check_jenkins_instance,
)
