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

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

DESCRIPTION = """Verifies that the current tuned profile matches the expected setting. Returns WARN if
the active profile differs from the desired one. Useful for ensuring consistent
performance tuning across a fleet of servers."""

CMD = 'tuned-adm active'
DEFAULT_TUNED_PROFILE = 'virtual-guest'


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(
        '--profile',
        default=DEFAULT_TUNED_PROFILE,
        dest='TUNED_PROFILE',
        help='Expected tuned profile name (case-insensitive). '
        'Example: `--profile virtual-guest`. '
        'Default: %(default)s',
    )

    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
    success, result = lib.shell.shell_exec(CMD)
    if not success:
        lib.base.cu('tuned is not applicable to your system.')
    stdout, _stderr, _retc = result
    tuned_profile = stdout.strip()

    # over and out
    # calculating the final check state
    tuned_profile = tuned_profile.lower().replace('current active profile: ', '')
    if tuned_profile == args.TUNED_PROFILE.lower():
        lib.base.oao(f'tuned profile is "{tuned_profile}" (as expected).', STATE_OK)
    else:
        lib.base.oao(
            f'tuned profile is "{tuned_profile}",'
            f' but supposed to be "{args.TUNED_PROFILE}".',
            STATE_WARN,
            always_ok=args.ALWAYS_OK,
        )


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