#!/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  # pylint: disable=C0413
import os  # pylint: disable=C0413
import sys  # pylint: disable=C0413

import lib.base  # pylint: disable=C0413
import lib.version  # pylint: disable=C0413
from lib.globals import (STATE_OK, STATE_UNKNOWN)

try:
    import psutil  # pylint: disable=C0413
except ImportError:
    print('Python module "psutil" is not installed.')
    sys.exit(STATE_UNKNOWN)


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

DESCRIPTION = """Return the average system load per CPU over the last 1, 5 and 15 minutes.
                 In short, "load" is the average sum of the number of processes waiting in the
                 run-queue plus the number currently executing over 1, 5, and 15 minute time
                 periods."""

DEFAULT_WARN = 1.15  # load divided by all cpus
DEFAULT_CRIT = 5.00  # load divided by all cpus


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='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '-c', '--critical',
        help='Set the critical threshold for load15 per CPU. '
             'Default: %(default)s',
        dest='CRIT',
        type=float,
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '-w', '--warning',
        help='Set the warning threshold for load15 per CPU. '
             'Default: %(default)s',
        dest='WARN',
        type=float,
        default=DEFAULT_WARN,
    )

    return parser.parse_args()


def main():
    """The main function. Hier spielt die Musik.
    """

    # parse the command line, exit with UNKNOWN if it fails
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    # fetch data
    if lib.version.version(psutil.__version__) < lib.version.version('5.6.2'):
        # Linux only
        load1, load5, load15 = [x / psutil.cpu_count() for x in os.getloadavg()]
    else:
        # OS-independent
        load1, load5, load15 = [x / psutil.cpu_count() for x in psutil.getloadavg()]

    # init some vars
    msg = ''
    state = lib.base.get_state(load15, float(args.WARN), float(args.CRIT), _operator='ge')
    perfdata = ''

    # build the message
    msg += f'Avg per CPU: {load1:0.2f} {load5:0.2f} {load15:0.2f}'
    perfdata += lib.base.get_perfdata('load1', load1, None, args.WARN, args.CRIT, 0, None)
    perfdata += lib.base.get_perfdata('load5', load5, None, args.WARN, args.CRIT, 0, None)
    perfdata += lib.base.get_perfdata('load15', load15, None, args.WARN, args.CRIT, 0, None)

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


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