#!/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 crypto policy against a desired one,
                 and returns a warning on a non-match."""

CMD = 'update-crypto-policies --show'
DEFAULT_CRYPTO_POLICY = 'DEFAULT'


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(
        '--policy',
        default=DEFAULT_CRYPTO_POLICY,
        dest='CRYPTO_POLICY',
        help='The expected crypto policy (full name), for example "FUTURE"'
             ' (case-insensitive). Default: %(default)s',
    )

    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('Crypto policies are not applicable to your system.')
    stdout, stderr, retc = result
    crypto_policy = stdout.strip()

    # over and out
    # calculating the final check state
    if crypto_policy.lower() == args.CRYPTO_POLICY.lower():
        lib.base.oao('Crypto policy is "{}" (as expected).'.format(
            crypto_policy,
        ), STATE_OK)
    lib.base.oao('Crypto policy is "{}", but supposed to be "{}".'.format(
        crypto_policy, args.CRYPTO_POLICY),
        STATE_WARN,
        always_ok=args.ALWAYS_OK,
    )


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