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

import itertools

_flatten = itertools.chain.from_iterable

###########################################################################
# NOTE: This check (and associated special agent) is deprecated and will be
#       removed in Checkmk version 2.2.
###########################################################################


def _has_tls(path, hosts):
    """Return True if path is available over TLS, otherwise return False."""
    return path.split("/", 1)[0] in _flatten(iter(hosts.values()))


def _iter_backends(parsed):
    for data in sorted(parsed.values()):
        for backend in data["backends"]:
            yield backend, data


def inventory_k8s_ingress_infos(parsed):
    for backend, _ in _iter_backends(parsed):
        yield (backend[0], None)


def check_k8s_ingress_infos(item, params, parsed):
    for backend, data in _iter_backends(parsed):
        if backend[0] != item:
            continue
        ports = [backend[-1]]
        if _has_tls(backend[0], data["hosts"]):
            ports.append(443)
        yield 0, "Ports: %s" % ", ".join(map(str, ports))
        yield 0, "Service: %s:%s" % (backend[1], backend[2])


check_info["k8s_ingress_infos"] = {
    # section is already migrated
    "inventory_function": inventory_k8s_ingress_infos,
    "check_function": check_k8s_ingress_infos,
    "service_description": "Ingress %s",
}
