#!/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.lftest
import lib.time
import lib.url
from lib.globals import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Checks whether PHP-FPM is alive by fetching its ping monitoring page. Alerts when the
reply differs from the expected "pong" or the page cannot be fetched at all, at the level
`--severity` sets. Reports how long the page took to answer."""

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_RESPONSE = 'pong'
DEFAULT_SEVERITY = 'warn'
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost/fpm-ping'


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

    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-perfdata',
        help=lib.args.help('--no-perfdata'),
        dest='NO_PERFDATA',
        action='store_true',
        default=False,
    )

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

    parser.add_argument(
        '--proxy',
        help=lib.args.help('--proxy'),
        dest='PROXY',
        default=None,
    )

    parser.add_argument(
        '--response',
        help='Expected PHP-FPM ping response string. Default: %(default)s',
        dest='RESPONSE',
        default=DEFAULT_RESPONSE,
    )

    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',
        '--url',
        help='PHP-FPM ping URL. 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
    response_time = None
    if args.TEST is None:
        start = lib.time.now(as_type='float')
        success, result = lib.url.fetch(
            args.URL,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            proxy=args.PROXY,
            timeout=args.TIMEOUT,
        )
        if not success:
            # A ping that does not come back is the very thing this check exists
            # for, not a problem of the check: a pool worker answers the page
            # (`fpm_status_handle_request()` runs in the worker's request loop),
            # so a timeout means every worker is busy or stuck, and a refused
            # connection that PHP-FPM or the web server in front of it is down.
            state = STATE_CRIT if args.SEVERITY == 'crit' else STATE_WARN
            lib.base.oao(
                f'{result}{lib.base.state2str(state, prefix=" ")}\n\n'
                f'A pool worker answers the ping, so a timeout means every worker'
                f' is busy or stuck (see php-fpm-status and php-fpm-logfile), and a'
                f' refused connection means PHP-FPM or the web server in front of'
                f' it is not running.',
                state,
                always_ok=args.ALWAYS_OK,
            )
        response_time = lib.time.now(as_type='float') - start
    else:
        # do not call the command, put in test data
        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = stdout

    # init some vars
    perfdata = ''

    # analyze data
    if result != args.RESPONSE:
        state = STATE_CRIT if args.SEVERITY == 'crit' else STATE_WARN
    else:
        state = STATE_OK

    # build the message
    msg = f'{result}{lib.base.state2str(state, prefix=" ")}'
    if response_time is not None:
        perfdata += lib.base.get_perfdata(
            'response_time',
            round(response_time, 3),
            uom='s',
            _min=0,
        )

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


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