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

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

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

DESCRIPTION = """Checks the current mode of SELinux against a desired mode,
                 and returns a warning on a non-match."""

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='%(prog)s: v{} by {}'.format(__version__, __author__),
    )

    parser.add_argument(
        '--always-ok',
        help='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--mode',
        default=DEFAULT_SELINUX_MODE,
        dest='SELINUX_MODE',
        help='The expected SELinux mode, one of "enforcing", "permissive" or "disabled"'
             ' (case-insensitive). Default: %(default)s',
        choices=['enforcing', 'permissive', 'disabled'],
    )

    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)

    # execute the shell command and return its result and exit code
    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('SELinux mode is "{}" (as expected).{}'.format(
            selinux_mode,
            msg_body,
        ), STATE_OK)
    lib.base.oao('SELinux mode is "{}", but supposed to be "{}".{}'.format(
        selinux_mode,
        args.SELINUX_MODE,
        msg_body,
    ), STATE_WARN, always_ok=args.ALWAYS_OK)


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