#!/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 check_icmp_arguments(params):
    args = []

    min_successful_pings = params.get("min_pings", 0)
    if min_successful_pings:
        args += ["-m", "%d" % min_successful_pings]

    rta = 200, 500
    loss = 80, 100
    for key, value in params.items():
        if key == "timeout":
            args += ["-t", str(value)]
        elif key == "packets":
            args += ["-n", str(value)]
        elif key == "rta":
            rta = value
        elif key == "loss":
            loss = value
    args += ["-w", "%.2f,%d%%" % (rta[0], loss[0])]
    args += ["-c", "%.2f,%d%%" % (rta[1], loss[1])]

    target = params.get("address", "address")

    # Note: The following macros have to work with both Nagios and the CMC
    if target == "address":
        if is_ipv6_primary(host_name()):
            args.append('-6')
        args.append("$HOSTADDRESS$")

    elif target == "alias":
        if is_ipv6_primary(host_name()):
            args.append('-6')
        args.append("$HOSTALIAS$")

    elif target == "all_ipv4addresses":
        args += ["$_HOSTADDRESSES_4$", "$_HOSTADDRESS_4$"]

    elif target == "all_ipv6addresses":
        args += ["-6", "$_HOSTADDRESSES_6$", "$_HOSTADDRESS_6$"]

    elif target == "additional_ipv4addresses":
        args.append("$_HOSTADDRESSES_4$")

    elif target == "additional_ipv6addresses":
        args += ["-6", "$_HOSTADDRESSES_6$"]

    elif target[0] == "indexed_ipv4address":
        args.append("$_HOSTADDRESS_4_%s$" % target[1])

    elif target[0] == "indexed_ipv6address":
        args.append("$_HOSTADDRESS_6_%s$" % target[1])

    else:  # custom
        args.append(str(target[1]))

    # Unfortunately, we must return a single string here.
    # Otherwise shell quoting will be applied to every element
    # of the list, which will interfere with macro replacements like
    # "$_HOSTADDRESSES_4$" -> "1.2.3.4 5.6.7.8"
    return " ".join(args)


def check_icmp_description(params):
    if "description" in params:
        return params["description"]

    description = "PING"
    target = params.get("address", "address")
    if target[0] == "indexed_ipv4address":
        description += " IPv4/%s" % target[1]
    elif target[0] == "indexed_ipv6address":
        description += " IPv6/%s" % target[1]
    return description


active_check_info['icmp'] = {
    "command_line": 'check_icmp $ARG1$',
    "argument_function": check_icmp_arguments,
    "service_description": check_icmp_description,
    "has_perfdata": True,
}
