#!/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 socket
import sys

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

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

DESCRIPTION = """Sends host notifications using the Rocket.Chat API."""

TIMEOUT = 4  # 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.',
        dest='DATETIME',
        required=True,
    )

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

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

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

    parser.add_argument(
        '--hostname',
        help='Set the hostname.',
        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.',
        dest='NOTIFICATION_AUTHOR',
    )

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

    parser.add_argument(
        '--rocketchat-mentions',
        help='Set the Rocket.Chat mentions. Can be specified multiple times.',
        action='append',
        default=None,
        dest='ROCKETCHAT_MENTIONS',
    )

    parser.add_argument(
        '--rocketchat-url',
        help='Set the Rocket.Chat Webhook API URL.',
        dest='ROCKETCHAT_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
    message = (
        f'{args.HOST_STATE:.4}:'
        f' {args.HOST_DISPLAYNAME}'
        f' ({args.DATETIME})\n'
        f'```\n'
        f'{args.HOST_OUTPUT}\n'
        f'```'
    )

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

    # short hostname of the monitoring host sending the notification
    notifying_hostname = socket.gethostname().split('.', 1)[0]
    icingaweb2_url = lib.icinga.build_icingaweb2_url(args.ICINGAWEB2_URL, args.HOSTNAME)

    if args.ROCKETCHAT_MENTIONS:
        message += '\n'
        for mention in args.ROCKETCHAT_MENTIONS:
            message += f'@{mention} '

    if args.HOST_STATE == 'UP':
        icon = ':host_up:'
    elif args.HOST_STATE == 'DOWN':
        icon = ':host_down:'
    else:
        icon = ':Pingu:'

    if icingaweb2_url:
        data = {
            'icon_emoji': icon,
            'text': message,
            'attachments': [
                {
                    'title': notifying_hostname,
                    'title_link': icingaweb2_url,
                }
            ],
        }
    else:
        data = {
            'emoji': icon,
            'text': message,
        }

    # over and out
    lib.base.coe(lib.rocket.send_message(args.ROCKETCHAT_URL, data, timeout=TIMEOUT))


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