#!/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_ldap_arguments(params):

    _name, basedn, settings = params
    args = []

    if "hostname" in settings:
        args += ["-H", settings["hostname"]]
    else:
        args += ["-H", "$HOSTADDRESS$"]

    args += ["-b", basedn]

    if "response_time" in settings:
        warn, crit = settings["response_time"]
        args += ["-w", "%f" % (warn / 1000.0), "-c", "%f" % (crit / 1000.0)]

    if "timeout" in settings:
        args += ["-t", settings["timeout"]]

    if "attribute" in settings:
        args += ["-a", settings["attribute"]]

    if "authentication" in settings:
        binddn, password = settings["authentication"]
        args += ["-D", binddn, "-P", passwordstore_get_cmdline("%s", password)]

    if "port" in settings:
        args += ["-p", settings["port"]]

    if "version" in settings:
        args += {
            "v2": ["-2"],
            "v3": ["-3"],
            "v3tls": ["-3", "-T"],
        }[settings["version"]]

    if settings.get("ssl"):
        args.append("--ssl")

    return args


def check_ldap_desc(params):
    if params[0].startswith("^"):
        return params[0][1:]
    return "LDAP %s" % params[0]


active_check_info["ldap"] = {
    "command_line": "check_ldap $ARG1$",
    "argument_function": check_ldap_arguments,
    "service_description": check_ldap_desc,
    "has_perfdata": True,
}
