#!/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 system-wide cryptographic policy (as reported by
update-crypto-policies) matches the expected setting. Returns WARN if the current
policy differs from the desired one (default: "DEFAULT"). Useful for ensuring
consistent TLS and cipher configurations across a fleet of servers."""

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=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(
        '--policy',
        default=DEFAULT_CRYPTO_POLICY,
        dest='CRYPTO_POLICY',
        help='Expected crypto policy name. '
        'Case-insensitive. '
        'Example: `FUTURE`. '
        '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('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(f'Crypto policy is "{crypto_policy}" (as expected).', STATE_OK)
    else:
        lib.base.oao(
            f'Crypto policy is "{crypto_policy}",'
            f' but supposed to be "{args.CRYPTO_POLICY}".',
            STATE_WARN,
            always_ok=args.ALWAYS_OK,
        )


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