#!/usr/bin/env python3
# -*- 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 base64
import sys
import xml.etree.ElementTree as ET  # nosec B405

import lib.args
import lib.base
import lib.lftest
import lib.txt
import lib.url
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Monitors virtual services on a KEMP LoadMaster appliance via its REST API. Alerts
when any virtual service or its real servers are in a non-operational state."""

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_PORT = 443
DEFAULT_SEVERITY = 'warn'
DEFAULT_TIMEOUT = 3


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(description=DESCRIPTION)

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

    parser.add_argument(
        '--always-ok',
        help=lib.args.help('--always-ok'),
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--filter',
        help='Only check virtual services whose NickName contains this string.',
        dest='FILTER',
        type=str,
    )

    parser.add_argument(
        '-H',
        '--hostname',
        help='KEMP LoadMaster appliance address, can be a hostname or IP address.',
        dest='HOSTNAME',
        required=True,
    )

    parser.add_argument(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--no-proxy',
        help=lib.args.help('--no-proxy'),
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

    parser.add_argument(
        '--password',
        help='KEMP REST API password.',
        dest='PASSWORD',
        required=True,
    )

    parser.add_argument(
        '--port',
        help='KEMP LoadMaster appliance port. Default: %(default)s',
        dest='PORT',
        default=DEFAULT_PORT,
    )

    parser.add_argument(
        '--severity',
        help=lib.args.help('--severity') + ' Default: %(default)s',
        dest='SEVERITY',
        default=DEFAULT_SEVERITY,
        choices=['warn', 'crit'],
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    parser.add_argument(
        '-u',
        '--username',
        help='KEMP REST API username.',
        dest='USERNAME',
        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)

    # fetch data
    if args.TEST is None:
        # https://support.kemptechnologies.com/hc/en-us/articles/10113769677581-RESTful-API-Programmer-Guide
        # get the values the normal way
        url = f'https://{args.HOSTNAME}:{args.PORT}/access/listvs'

        # authorization
        auth = f'{args.USERNAME}:{args.PASSWORD}'
        encoded_auth = lib.txt.to_text(base64.b64encode(lib.txt.to_bytes(auth)))

        result = lib.base.coe(
            lib.url.fetch(
                url,
                insecure=args.INSECURE,
                no_proxy=args.NO_PROXY,
                timeout=args.TIMEOUT,
                header={'Authorization': f'Basic {encoded_auth}'},
            )
        )
    else:
        # do not call the command, put in test data
        result, _stderr, _retc = lib.lftest.test(args.TEST)

    # init some vars
    state = STATE_OK
    perfdata = ''
    count = 0
    table = []

    # analyze data
    # response comes from the admin-configured Kemp LB API, not from untrusted
    # end-user input; defusedxml would require an additional dependency
    for service in ET.fromstring(result).findall('.Success/Data/VS'):  # nosec B314
        name = service.find('NickName').text
        if not args.FILTER or args.FILTER in name:
            count += 1
            status = service.find('Status').text  # = Up, Down, Unchecked
            if status.lower() == 'down':
                service_state = lib.base.str2state(args.SEVERITY)
                status = f'{status}{lib.base.state2str(service_state, prefix=" ")}'
                state = lib.base.get_worst(state, service_state)
            table.append(
                {
                    'name': name,
                    'status': status,
                }
            )

    # build the message
    msg = f'{count} {lib.txt.pluralize("service", count)} checked. '
    if len(table) > 0:
        msg += '\n\n' + lib.base.get_table(
            table,
            ['name', 'status'],
            header=['NickName', 'Status'],
        )
    perfdata += lib.base.get_perfdata(
        'services',
        count,
        _min=0,
    )

    # over and out
    lib.base.oao(msg, state, perfdata, always_ok=args.ALWAYS_OK)


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