#!/usr/bin/env python3
# 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.

from cmk.base.check_api import passwordstore_get_cmdline


def check_mailboxes_arguments(params):
    """
    >>> for l in check_mailboxes_arguments({  # v2.1.0 / EWS
    ...     'service_description': 'SD',
    ...     'fetch': ('EWS', {
    ...       'server': 'srv', 'connection': {},
    ...       'auth': ('usr', ('password', 'pw')),
    ...       'email_address': 'usr@srv.com',
    ...       'connection': {'disable_tls': True, 'disable_cert_validation': False, 'tcp_port': 123}}),
    ...     'age': (1, 2), 'age_newest': (3, 4), 'count': (5, 6),
    ...     'mailboxes': ['abc', 'def']}):
    ...   print(l)
    --fetch-protocol=EWS
    --fetch-server=srv
    --fetch-port=123
    --fetch-username=usr
    --fetch-password=pw
    --fetch-email-address=usr@srv.com
    --warn-age-oldest=1
    --crit-age-oldest=2
    --warn-age-newest=3
    --crit-age-newest=4
    --warn-count=5
    --crit-count=6
    --mailbox=abc
    --mailbox=def
    """
    try:
        fetch_protocol, fetch_params = params["fetch"]
        connection_params = fetch_params["connection"]
        username, password = fetch_params["auth"]
    except KeyError as exc:
        raise ValueError(
            f"Params for check_mailboxes are faulty (missing {exc}), did you update the config?"
        )

    args = [
        f"--fetch-protocol={fetch_protocol}",
        f"--fetch-server={fetch_params.get('server', '$HOSTADDRESS$')}",
    ]

    # NOTE: this argument will be turned into `--fetch-disable-tls` when
    # refactoring all mailbox based active checks
    if not connection_params.get("disable_tls"):
        args.append("--fetch-tls")

    if connection_params.get("disable_cert_validation"):
        args.append("--fetch-disable-cert-validation")

    if (fetch_port := connection_params.get("tcp_port")) is not None:
        args.append(f"--fetch-port={fetch_port}")

    args.append(f"--fetch-username={username}")
    args.append(passwordstore_get_cmdline("--fetch-password=%s", password))

    if "email_address" in fetch_params:
        args.append(f"--fetch-email-address={fetch_params['email_address']}")

    if "connect_timeout" in params:
        args.append(f"--connect-timeout={params['connect_timeout']}")

    if "retrieve_max" in params:
        args.append(f"--retrieve-max={params['retrieve_max']}")

    if "age" in params:
        warn, crit = params["age"]
        args += [f"--warn-age-oldest={warn}", f"--crit-age-oldest={crit}"]

    if "age_newest" in params:
        warn, crit = params["age_newest"]
        args += [f"--warn-age-newest={warn}", f"--crit-age-newest={crit}"]

    if "count" in params:
        warn, crit = params["count"]
        args += [f"--warn-count={warn}", f"--crit-count={crit}"]

    for mb in params.get("mailboxes", []):
        args.append(f"--mailbox={mb}")

    return args


active_check_info["mailboxes"] = {
    "command_line": "check_mailboxes $ARG1$",
    "argument_function": check_mailboxes_arguments,
    "service_description": lambda params: params["service_description"],
    "has_perfdata": True,
}
