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

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

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

DESCRIPTION = """Monitors Apache mod_qos status via the machine-readable status handler. Reports current
connection and request limits, active connections, and quality of service metrics.
Alerts when connection or request limits are approached."""

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 8
DEFAULT_URL = 'http://localhost/qos-status'


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(
        '--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(
        '--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',
        '--url',
        help='URL of the mod_qos machine-readable status handler. Default: %(default)s',
        dest='URL',
        default=DEFAULT_URL,
    )

    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:
        url = args.URL
        if url[0:4] != 'http':
            lib.base.cu('--url parameter has to start with "http://" or https://".')
        url = url + '?auto'

        # fetch the url
        result = lib.base.coe(
            lib.url.fetch(
                url,
                insecure=args.INSECURE,
                no_proxy=args.NO_PROXY,
                timeout=args.TIMEOUT,
            )
        )
    else:
        # do not call the command, put in test data
        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = stdout

    result = result.strip().split('\n')

    # init some vars
    msg = 'Everything is ok.\n\n'
    state = STATE_OK
    perfdata = ''
    table_values = []

    # analyze data
    for line in result:
        # ignore the optional line containing "b;system.load: 0.12"
        if 'system.load: ' in line:
            continue
        items = line.split(';')
        # Len 4: ['b', 'h1-proxy01.linuxfabrik.it', '0', 'QS_AllConn: 283']
        # Len 5: ['v', 'www.example.com', '443', 'QS_LocKBytesPerSecLimitMatch', '1250[^.*$]: 14']
        htype = 'virt' if items[0] == 'v' else 'base'
        try:
            host = items[1]
            port = items[2]
            if len(items) == 4:
                values = items[3].split(': ')
                key = values[0]
                pattern = 'Global'
                configured_value = None
                current_value = values[1]
            else:
                values = items[4].split(': ')
                key = items[3]
                configured = values[0]
                pattern = configured[configured.find('[') :]
                configured_value = configured[0 : configured.find('[')]
                current_value = values[1]
        except Exception:
            lib.base.cu('Malformed mod_qos status info.')

        perfdata += lib.base.get_perfdata(
            f'{key}_{pattern}',
            current_value,
            uom='KB' if 'KBytes' in key else None,
            _min=0,
            _max=configured_value if configured_value is not None else None,
        )

        table_values.append(
            {
                'htype': htype,
                'host': host,
                'port': port,
                'key': key,
                'pattern': pattern,
                'configured_value': configured_value,
                'current_value': current_value,
            }
        )

    # build the message
    msg += lib.base.get_table(
        table_values,
        [
            'htype',
            'host',
            'port',
            'key',
            'pattern',
            'configured_value',
            'current_value',
        ],
        header=['Type', 'Host', 'Port', 'Key', 'ReqPttrn', 'Configured', 'Current'],
    )

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


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