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

__author__ = """Linuxfabrik GmbH, Zurich/Switzerland;
                originally written by Dominik Riva, Universitätsspital Basel/Switzerland"""
__version__ = '2026040801'

DESCRIPTION = """Checks the current state of a Gemalto SafeNet ProtectServer Network HSM via SSH by
running a PSESH command on the appliance. Alerts when the HSM adapter reports a
non-operational state."""

DEFAULT_COMMAND = 'hsm state'
DEFAULT_CRIT = 90
DEFAULT_SEVERITY = 'crit'
DEFAULT_TIMEOUT = 3
DEFAULT_USERNAME = 'pseoperator'
DEFAULT_WARN = 80


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(
        '-c',
        '--critical',
        help=lib.args.help('--critical') + ' Default: >= %(default)s',
        dest='CRIT',
        type=int,
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '-H',
        '--hostname',
        help='SafeNet HSM hostname or IP address.',
        dest='HOSTNAME',
        required=True,
    )

    parser.add_argument(
        '-p',
        '--password',
        help='SafeNet HSM password.',
        dest='PASSWORD',
        required=True,
    )

    parser.add_argument(
        '--severity',
        help=lib.args.help('--severity') + ' Default: %(default)s',
        dest='SEVERITY',
        default=DEFAULT_SEVERITY,
        choices=['warn', 'crit'],
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    parser.add_argument(
        '-u',
        '--username',
        help='SafeNet HSM username. Example: `--username admin`. Default: %(default)s',
        dest='USERNAME',
        choices=['admin', 'pseoperator'],
        default=DEFAULT_USERNAME,
    )

    parser.add_argument(
        '-w',
        '--warning',
        help=lib.args.help('--warning') + ' Default: >= %(default)s',
        dest='WARN',
        type=int,
        default=DEFAULT_WARN,
    )

    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
    if args.TEST is None:
        # -o: Give options in the format used in the configuration file.
        # -T: Disable pseudo-terminal allocation.
        cmd = (
            f'sshpass -p {args.PASSWORD}'
            f' ssh -o ConnectTimeout={args.TIMEOUT}'
            f" -T '{args.USERNAME}'@'{args.HOSTNAME}'"
            f" 'hsm state'"
        )
        stdout, stderr, retc = lib.base.coe(lib.shell.shell_exec(cmd))
        if lib.shell.RETC_SSHPASS.get(retc, ''):
            lib.base.cu(f'sshpass: {lib.shell.RETC_SSHPASS[retc]}')
        if stderr:
            lib.base.cu(stderr)
    else:
        # do not call the command, put in test data
        stdout, stderr, retc = lib.lftest.test(args.TEST)

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''

    # analyze data
    stdout = stdout.strip()  # remove the empty line at the start of the output
    if 'HSM in NORMAL MODE' not in stdout or 'Command Result : 0' not in stdout:
        state = lib.base.str2state(args.SEVERITY)
    value = lib.txt.extract_str(stdout, 'Level=', '%')
    if value:
        state = lib.base.get_worst(
            state, lib.base.get_state(value, args.WARN, args.CRIT)
        )
        perfdata += lib.base.get_perfdata(
            'usage_percent',
            value,
            uom='%',
            warn=args.WARN,
            crit=args.CRIT,
            _min=0,
            _max=100,
        )

    # build the message
    first_line = ' '.join(stdout.partition('\n')[0].split())
    msg = f'{first_line}{lib.base.state2str(state, prefix=" ")}'

    # over and out
    lib.base.oao(msg, state, perfdata, always_ok=args.ALWAYS_OK)


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