#!/usr/lib64/linuxfabrik-monitoring-plugins/venv/bin/python
# -*- 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 json
import sys

import lib.args
import lib.base
import lib.huawei_dorado
import lib.lftest
import lib.time
import lib.txt
from lib.globals import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Lists the current alarms of a Huawei OceanStor Dorado storage system via the REST
API (/alarm/currentalarm endpoint). Alerts when alarms are present: critical if any critical alarm
exists, warning for a major or a warning alarm."""

DEFAULT_CACHE_EXPIRE = 15  # minutes; default session timeout period is 20 minutes
DEFAULT_DEVICE_ID = ''  # the appliance reports its own at login
DEFAULT_INSECURE = True
DEFAULT_NO_MATCH_SEVERITY = 'ok'
DEFAULT_NO_PROXY = False
DEFAULT_SCOPE = '0'
DEFAULT_TIMEOUT = 3

# Fields `--match` is applied to.
MATCH_FIELDS = ('name', 'description', 'location')

# The alarm endpoint returns at most 250 objects per request, which is its own
# limit rather than the 100 the other list endpoints use.
PAGE_SIZE = 250

# Ask for UTC timestamps. The appliance otherwise answers in whatever timezone it
# is set to, without saying which, and the check cannot turn that back into a point
# in time.
TIME_CONVERSION_UTC = 0


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        epilog=lib.args.epilog(__file__),
        formatter_class=lib.args.HelpFormatter,
    )

    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(
        '--cache-expire',
        help=lib.args.help('--cache-expire') + ' Default: %(default)s',
        dest='CACHE_EXPIRE',
        type=int,
        default=DEFAULT_CACHE_EXPIRE,
    )

    parser.add_argument(
        '--device-id',
        help='Huawei OceanStor Dorado API device ID. '
        'Optional: the appliance reports its own at login, so this is only '
        'needed to override that answer.',
        dest='DEVICE_ID',
        default=DEFAULT_DEVICE_ID,
    )

    parser.add_argument(
        '--ignore',
        help='Skip alarms. '
        + lib.args.help('--ignore-regex')
        + ' The regex is anchored at the start of the string (Python `re.match`) and '
        'is matched against the alarm name, its description and the module it occurred '
        'on, so prefix with `.*` to match anywhere. Default: %(default)s',
        dest='IGNORE',
        action='append',
        default=None,
    )

    parser.add_argument(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--match',
        help='Limit to alarms. '
        + lib.args.help('--match')
        + ' The regex is anchored at the start of the string (Python `re.match`) and '
        'is matched against the alarm name, its description and the module it occurred '
        'on, so prefix with `.*` to match anywhere. Default: %(default)s',
        dest='MATCH',
        action='append',
        default=None,
    )

    parser.add_argument(
        '--no-insecure',
        help=lib.args.help('--no-insecure'),
        dest='INSECURE',
        action='store_false',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--no-match-severity',
        help=lib.args.help('--no-match-severity') + ' Default: %(default)s',
        dest='NO_MATCH_SEVERITY',
        choices=['ok', 'warn', 'crit', 'unknown'],
        default=DEFAULT_NO_MATCH_SEVERITY,
    )

    parser.add_argument(
        '--no-perfdata',
        help=lib.args.help('--no-perfdata'),
        dest='NO_PERFDATA',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--no-proxy',
        help=lib.args.help('--no-proxy'),
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

    parser.add_argument(
        '--password',
        help='Huawei OceanStor Dorado API password.',
        dest='PASSWORD',
    )

    parser.add_argument(
        '--password-file',
        help=lib.args.help('--password-file'),
        dest='PASSWORD_FILE',
    )

    parser.add_argument(
        '--scope',
        help='Huawei OceanStor Dorado API scope.',
        dest='SCOPE',
        default=DEFAULT_SCOPE,
    )

    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',
        '--url',
        help='Huawei OceanStor Dorado API URL.',
        dest='URL',
        required=True,
    )

    parser.add_argument(
        '--username',
        help='Huawei OceanStor Dorado API username.',
        dest='USERNAME',
        required=True,
    )

    parser.add_argument(
        '-v',
        '--verbose',
        help=lib.args.help('--verbose')
        + ' Appends what every API request returned, so the appliance\'s own answers '
        'can be read while working out how it reports something. Session tokens are '
        'redacted. The output is as long as those answers are, so this is a debugging '
        'aid rather than something to leave switched on.',
        dest='VERBOSE',
        action='store_true',
        default=False,
    )

    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)

    if args.PASSWORD_FILE:
        args.PASSWORD = lib.args.load_secret(args.PASSWORD_FILE)
    if not args.PASSWORD:
        lib.base.cu('Provide the API password via --password or --password-file.')

    # set default values for append parameters that were not specified
    if args.IGNORE is None:
        args.IGNORE = []
    if args.MATCH is None:
        args.MATCH = []

    if not args.URL.startswith('http'):
        lib.base.cu('--url parameter has to start with "http://" or https://".')

    # fetch data
    truncated = False
    if args.TEST is None:
        result, truncated = lib.huawei_dorado.get_all_data(
            f'alarm/currentalarm?timeConversion={TIME_CONVERSION_UTC}',
            args,
            page_size=PAGE_SIZE,
        )
    else:
        # do not call the command, put in test data
        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = json.loads(stdout)

    # no valuable result?
    lib.huawei_dorado.assert_ok(result, 'the current alarms')

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''
    compiled_match_regex = [
        lib.base.coe(item) for item in lib.txt.compile_regex(args.MATCH, '--match')
    ]
    compiled_ignore_regex = [
        lib.base.coe(item)
        for item in lib.txt.compile_regex(args.IGNORE, '--ignore')
    ]
    counts = {2: 0, 3: 0, 5: 0, 6: 0}

    # analyze data
    table_data = []
    for alarm in result.get('data') or []:
        # The appliance embeds HTML entities in the texts it generates, so `&#40;` would
        # otherwise reach the output as those five characters instead of the bracket it
        # stands for. Decoded before filtering, so `--match` sees what the reader sees.
        for field in ('description', 'location', 'name'):
            alarm[field] = str(alarm.get(field, ''))
        alarm = lib.txt.unescape(alarm, keys=('description', 'location', 'name'))

        if args.MATCH and not any(
            lib.base.coe(lib.txt.match_regex(pattern, str(alarm.get(field, ''))))
            for pattern in compiled_match_regex
            for field in MATCH_FIELDS
        ):
            continue

        if args.IGNORE and any(
            lib.base.coe(lib.txt.match_regex(pattern, str(alarm.get(field, ''))))
            for pattern in compiled_ignore_regex
            for field in MATCH_FIELDS
        ):
            continue

        severity = lib.huawei_dorado.as_code(alarm.get('level'))
        counts[severity] = counts.get(severity, 0) + 1
        alarm_state = lib.huawei_dorado.get_alarm_severity_state(alarm.get('level'))
        state = lib.base.get_worst(state, alarm_state)

        alarm['level'] = lib.huawei_dorado.get_alarm_severity(alarm.get('level'))
        alarm['startTime'] = lib.time.epoch2iso(alarm.get('startTime', 0))
        alarm['state'] = lib.base.state2str(alarm_state, empty_ok=False)

        table_data.append(alarm)

    # An appliance with no alarm at all is the normal case, and it is not the
    # same as a filter that selected none of the alarms it does have.
    if not table_data and args.MATCH:
        lib.base.oao(
            f'No alarms matched `{", ".join(args.MATCH)}`.',
            lib.base.str2state(args.NO_MATCH_SEVERITY),
            always_ok=args.ALWAYS_OK,
            no_perfdata=args.NO_PERFDATA,
        )

    # build the message
    perfdata += lib.base.get_perfdata(
        'critical_alarms', counts[6], uom=None, _min=0
    )
    perfdata += lib.base.get_perfdata('major_alarms', counts[5], uom=None, _min=0)
    perfdata += lib.base.get_perfdata('warning_alarms', counts[3], uom=None, _min=0)
    perfdata += lib.base.get_perfdata(
        'informational_alarms', counts[2], uom=None, _min=0
    )

    if truncated:
        # The walk hit its page cap, so this is a floor on the alarm count, not
        # the count itself.
        state = lib.base.get_worst(state, STATE_WARN)

    if state == STATE_CRIT:
        msg += 'There are critical alarms.'
    elif state == STATE_WARN:
        msg += 'There are alarms.'
    else:
        msg += 'Everything is ok.'

    if truncated:
        msg += (
            '\n\nThe appliance reports more alarms than this check reads in one run;'
            ' the list below is incomplete.'
        )

    # build table output
    if table_data:
        keys = ['sequence', 'startTime', 'level', 'name', 'location', 'state']
        headers = ['Sequence', 'Time', 'Severity', 'Name', 'Location', 'State']
        msg += '\n\n' + lib.base.get_table(
            table_data, keys, header=headers, missing='--', hide_empty=True
        )

    if args.VERBOSE:
        msg += '\n\n' + lib.huawei_dorado.format_responses()

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


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