#!/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 SELinux mode (enforcing, permissive, or disabled) matches
the expected setting. Returns WARN if the actual mode differs from the desired one."""

CMD = 'getenforce'
DEFAULT_SELINUX_MODE = 'enforcing'


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(
        '--mode',
        default=DEFAULT_SELINUX_MODE,
        dest='SELINUX_MODE',
        help='Expected SELinux mode, one of "enforcing", "permissive" or "disabled" (case-insensitive). '
        'Default: %(default)s',
        choices=['enforcing', 'permissive', 'disabled'],
    )

    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('SELinux is not applicable to your system.')
    stdout, _stderr, _retc = result
    selinux_mode = stdout.strip()

    # over and out
    # calculating the final check state
    msg_body = (
        '\nMake SELinux Enforcing Again.' if selinux_mode.lower() != 'enforcing' else ''
    )
    if selinux_mode.lower() == args.SELINUX_MODE.lower():
        lib.base.oao(
            f'SELinux mode is "{selinux_mode}" (as expected).{msg_body}', STATE_OK
        )
    lib.base.oao(
        (
            f'SELinux mode is "{selinux_mode}",'
            f' but supposed to be "{args.SELINUX_MODE}".'
            f'{msg_body}'
        ),
        STATE_WARN,
        always_ok=args.ALWAYS_OK,
    )


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