#!/usr/lib64/linuxfabrik-monitoring-plugins/venv/bin/python
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author:  Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
#          https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.md

"""See the check's README for more details."""

import argparse
import sys

import lib.args
import lib.base
import lib.icinga
import lib.url
from lib.globals import STATE_UNKNOWN

__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026070901'

DESCRIPTION = """Sends notifications for hosts using the Zoom Incoming Webhook API."""

TIMEOUT = 8  # seconds


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        epilog=lib.args.epilog(__file__, section='notification-plugins'),
        formatter_class=lib.args.HelpFormatter,
    )

    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version=f'%(prog)s: v{__version__} by {__author__}',
    )

    parser.add_argument(
        '--datetime',
        help='Set the message timestamp ($icinga.short_date_time$).',
        dest='DATETIME',
        required=True,
    )

    parser.add_argument(
        '--host-displayname',
        help='Set the display name of the host ($host.display_name$).',
        dest='HOST_DISPLAYNAME',
        required=True,
    )

    parser.add_argument(
        '--host-output',
        help='Set the host output ($host.output$).',
        dest='HOST_OUTPUT',
    )

    parser.add_argument(
        '--host-state',
        help='Set the host state ($host.state$).',
        dest='HOST_STATE',
        required=True,
    )

    parser.add_argument(
        '--hostname',
        help='Set the hostname ($host.name$).',
        dest='HOSTNAME',
    )

    parser.add_argument(
        '--icingaweb2-url',
        help='Set the Icinga Web 2 URL, for example "https://example.com/icingaweb2".',
        dest='ICINGAWEB2_URL',
    )

    parser.add_argument(
        '--notification-author',
        help='Set the author of the comment ($notification.author$).',
        dest='NOTIFICATION_AUTHOR',
    )

    parser.add_argument(
        '--notification-comment',
        help='Set the comment ($notification.comment$).',
        dest='NOTIFICATION_COMMENT',
    )

    parser.add_argument(
        '--token',
        help='Set the Zoom verification token.',
        dest='TOKEN',
        required=True,
    )

    parser.add_argument(
        '--url',
        help='Set the URL of the Zoom Incoming Webhook API.',
        dest='URL',
        required=True,
    )

    args, _ = parser.parse_known_args()
    return args


def main():
    """The main function. This is where the magic happens."""

    # parse the command line
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    # build the message
    head = f'{args.HOST_STATE:.4}: {args.HOST_DISPLAYNAME} ({args.DATETIME})'

    if args.NOTIFICATION_COMMENT:
        head += f'\nCOMMENT: {args.NOTIFICATION_COMMENT} ({args.NOTIFICATION_AUTHOR})'

    link = lib.icinga.build_icingaweb2_url(args.ICINGAWEB2_URL, args.HOSTNAME)

    data = {
        'head': {
            'text': head,
        },
        'body': [
            {
                'type': 'message',
                'text': args.HOST_OUTPUT,
                'link': link,
            }
        ],
    }

    # over and out
    result = lib.base.coe(
        lib.url.fetch(
            f'{args.URL}?format=full',
            header={
                'Content-Type': 'application/json',
                'Authorization': args.TOKEN,
            },
            data=data,
            encoding='serialized-json',
            extended=True,
            timeout=TIMEOUT,
        )
    )

    if result['status_code'] != 200 or result['response'] != 'OK':
        sys.exit(STATE_UNKNOWN)


if __name__ == '__main__':
    try:
        main()
    except Exception:
        lib.base.cu()
