#!/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.


def discover_docker_node_info(info):
    if info:
        yield None, {}


def check_docker_node_info(_no_item, _no_params, parsed):
    if "Name" in parsed:
        yield 0, "Daemon running on host %s" % parsed["Name"]
    for state, key in enumerate(("Warning", "Critical", "Unknown"), 1):
        if key in parsed:
            yield state, parsed[key]


check_info["docker_node_info"] = {
    # section is already migrated!
    "inventory_function": discover_docker_node_info,
    "check_function": check_docker_node_info,
    "service_description": "Docker node info",
}


def check_docker_node_containers(_no_item, params, parsed):

    for title, key, levels_prefix in (
        ("containers", "Containers", ""),
        ("running", "ContainersRunning", "running_"),
        ("paused", "ContainersPaused", "paused_"),
        ("stopped", "ContainersStopped", "stopped_"),
    ):

        count = parsed.get(key)
        if count is None:
            yield 3, "%s: count not present in agent output" % title.title()
            continue

        levels = params.get("%supper_levels" % levels_prefix, (None, None))
        levels_lower = params.get("%slower_levels" % levels_prefix, (None, None))
        yield check_levels(
            count,
            title,
            levels + levels_lower,
            human_readable_func=lambda x: "%d" % x,
            infoname=title.title(),
        )


check_info["docker_node_info.containers"] = {
    # section is already migrated!
    "inventory_function": discover_single,
    "check_function": check_docker_node_containers,
    "service_description": "Docker containers",
    "has_perfdata": True,
    "group": "docker_node_containers",
}
