#!/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 json
import sys

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

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

DESCRIPTION = """Checks the state of all physical drives, volumes and their storage controllers in a
Redfish-compatible server via the Redfish API. Alerts when any drive, volume or storage controller
reports a degraded or failed state. System-level health (processors, BIOS, power, temperature,
indicator LED, etc.) is deliberately ignored by this check so that a system warning unrelated
to storage does not mask the storage status; use `redfish-systems` for that."""

API_BASE = '/redfish/v1'
DEFAULT_CACHE_EXPIRE = (
    5  # minutes; also caches API responses, kept below the session timeout
)
DEFAULT_INSECURE = True
DEFAULT_NO_PROXY = False
DEFAULT_RETRIES = 3  # extra attempts on a failed Redfish request
DEFAULT_TIMEOUT = 8
DEFAULT_VERBOSE = False


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(
        '--brief',
        help='Hide items that are OK and show only those in WARN/CRIT state. '
        'Alerting is unaffected: all items still drive the overall check state.',
        dest='BRIEF',
        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(
        '--ignore',
        help='Ignore items whose name matches this Python regular expression. '
        'Case-sensitive by default; use `(?i)` for case-insensitive matching. '
        'Can be specified multiple times.',
        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(
        '--inventory',
        help='Output the parsed components as JSON on stdout and exit OK, instead of '
        'running a health check. Use this to collect a hardware inventory: the JSON is a '
        'single object keyed by component type, so the output of several Redfish checks can '
        'be merged into one inventory document with `jq --slurp`. Ignores --brief, --match '
        'and --ignore.',
        dest='INVENTORY',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--match',
        help='Only check items whose name matches this Python regular expression. '
        'Case-sensitive by default; use `(?i)` for case-insensitive matching. '
        'Can be specified multiple times. ' + lib.args.MATCH_IGNORE_PRECEDENCE,
        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-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='Redfish API password.',
        dest='PASSWORD',
    )

    parser.add_argument(
        '--proxy',
        help=lib.args.help('--proxy'),
        dest='PROXY',
        default=None,
    )

    parser.add_argument(
        '--retries',
        help='Number of extra attempts if a request to the Redfish API fails, before the '
        'check gives up. Helps against an occasionally slow or flaky management controller. '
        'Default: %(default)s',
        dest='RETRIES',
        type=int,
        default=DEFAULT_RETRIES,
    )

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

    parser.add_argument(
        '--username',
        help='Redfish API username.',
        dest='USERNAME',
    )

    parser.add_argument(
        '--verbose',
        help=lib.args.help('--verbose') + ' ' + lib.redfish.VERBOSE_HELP,
        dest='VERBOSE',
        action='store_true',
        default=DEFAULT_VERBOSE,
    )

    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)

    # --verbose: record every Redfish response for the output, where a bug report can pick
    # them up, and trace every request to a file. A file as well, because a check slow enough
    # to need diagnosing is usually one the monitoring server terminates for exceeding its
    # timeout, and a terminated check prints nothing at all.
    if args.VERBOSE:
        success, trace_path = lib.redfish.start_trace()
        if not success:
            lib.base.cu(trace_path)
        lib.redfish.record_responses()

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

    # compile the item filter regexes once
    ignore_patterns = [
        lib.base.coe(p) for p in lib.txt.compile_regex(args.IGNORE, '--ignore')
    ]
    match_patterns = [
        lib.base.coe(p) for p in lib.txt.compile_regex(args.MATCH, '--match')
    ]

    # fetch data
    if args.TEST is not None:
        # do not call the API, replay the responses a --verbose run recorded instead. The
        # code below then walks them exactly as it would walk the controller.
        stdout, _, _ = lib.lftest.test(args.TEST)
        lib.base.coe(lib.redfish.replay(stdout))
    if not args.URL.startswith('http'):
        lib.base.cu('--url parameter has to start with "http://" or https://".')
    header = {'Accept': 'application/json'}
    # cache_expire (seconds) enables the lib fetch layer's shared per-URL cache,
    # so sibling Redfish checks on this host share one session and each fetch.
    cache_expire = args.CACHE_EXPIRE * 60
    header.update(lib.redfish.get_auth_header(args, cache_expire=cache_expire))
    expand = lib.redfish.get_expand_suffix(
        args.URL,
        header=header,
        insecure=args.INSECURE,
        no_proxy=args.NO_PROXY,
        proxy=args.PROXY,
        timeout=args.TIMEOUT,
        retries=args.RETRIES,
        cache_expire=cache_expire,
    )
    # Entry point: the Systems collection, read in one request via the Redfish
    # $expand query and cached by the lib fetch layer so the sibling Redfish
    # checks on this host reuse it within the cache window.
    systems_url = f'{args.URL}{API_BASE}/Systems'
    result = lib.base.coe(
        lib.redfish.fetch_collection(
            systems_url,
            expand=expand,
            header=header,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            proxy=args.PROXY,
            timeout=args.TIMEOUT,
            retries=args.RETRIES,
            cache_expire=cache_expire,
        )
    )
    # "Members": [
    #     {
    #         "@odata.id": "/redfish/v1/Systems/437XR1138R2"
    #     }
    # ],
    if len(result.get('Members', [])) == 0:
        lib.base.cu('Nothing to check, no Redfish members found.')

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''
    member_count = 0
    drive_count = 0
    drive_not_ok = 0
    volume_count = 0
    volume_not_ok = 0
    controller_count = 0
    controller_not_ok = 0
    # only allocated and populated in --inventory mode, so a normal health
    # check holds nothing extra in memory
    inventory = (
        {'physical_drive': [], 'logical_drive': [], 'storage_controller': []}
        if args.INVENTORY
        else None
    )

    # analyze data: follow each "Member" link, aggregate drive and
    # storage-controller health into `state`. System-level health is
    # deliberately not aggregated (see `redfish-systems` for that).
    # fetch_members fills in any systems the controller left as bare references
    # (i.e. when it did not honour $expand on the collection above)
    system_members = lib.base.coe(
        lib.redfish.fetch_members(
            result.get('Members', []),
            args.URL,
            header=header,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            proxy=args.PROXY,
            timeout=args.TIMEOUT,
            retries=args.RETRIES,
            cache_expire=cache_expire,
        )
    )
    for systems in system_members:
        systems = lib.redfish.get_systems(systems)
        if systems['Status_State'] not in ['Enabled', 'Quiesced']:
            continue
        member_count += 1

        # build the message: only identify the member (manufacturer, model,
        # hostname, SKU, serial number). System-level health is intentionally
        # not aggregated here and not labelled with a state; use
        # `redfish-systems` for that.
        msg += 'Member:'
        msg += f' {systems["Manufacturer"]}' if systems['Manufacturer'] else ''
        msg += f' {systems["Model"]}' if systems['Model'] else ''
        msg += ', '
        msg += f'HostName: {systems["HostName"]}, ' if systems['HostName'] else ''
        msg += f'SKU: {systems["SKU"]}, ' if systems['SKU'] else ''
        msg += f'SerNo: {systems["SerialNumber"]}, ' if systems['SerialNumber'] else ''
        msg = msg[:-2]

        # get all available storage links for the member
        if not systems['Storage_@odata.id']:
            msg += '\n\n'
            continue

        # fetch_collection asks the controller to inline the members via the
        # Redfish $expand query, so the storage controllers are read in one
        # request instead of one per controller; fetch_members fills in any it
        # left as bare references.
        # "/redfish/v1/Systems/437XR1138R2/Storage"
        storages = lib.base.coe(
            lib.redfish.fetch_collection(
                lib.base.coe(
                    lib.redfish.build_url(args.URL, systems['Storage_@odata.id'])
                ),
                expand=expand,
                header=header,
                insecure=args.INSECURE,
                no_proxy=args.NO_PROXY,
                proxy=args.PROXY,
                timeout=args.TIMEOUT,
                retries=args.RETRIES,
                cache_expire=cache_expire,
            )
        )
        table_data = []
        table_data_drive = []
        table_data_volume = []
        for storage in storages.get('Members', []):
            # "/redfish/v1/Systems/437XR1138R2/Storage/RAID.SL.7-1". Expanding
            # the storage resource inlines its Drives and Volumes, collapsing
            # a shelf of disks into this single request where supported.
            storage_data = lib.base.coe(
                lib.redfish.fetch_collection(
                    lib.base.coe(lib.redfish.build_url(args.URL, storage['@odata.id'])),
                    expand=expand,
                    header=header,
                    insecure=args.INSECURE,
                    no_proxy=args.NO_PROXY,
                    proxy=args.PROXY,
                    timeout=args.TIMEOUT,
                    retries=args.RETRIES,
                    cache_expire=cache_expire,
                )
            )

            # get drives attached to the storage member. fetch_members fills in
            # any drives the controller left as bare references above.
            drive_members = lib.base.coe(
                lib.redfish.fetch_members(
                    storage_data.get('Drives', []),
                    args.URL,
                    header=header,
                    insecure=args.INSECURE,
                    no_proxy=args.NO_PROXY,
                    proxy=args.PROXY,
                    timeout=args.TIMEOUT,
                    retries=args.RETRIES,
                    cache_expire=cache_expire,
                )
            )
            for drive_data in drive_members:
                drive_data = lib.redfish.get_systems_storage_drives(drive_data)
                if drive_data['Status_State'] not in ['Enabled', 'Quiesced']:
                    continue
                # collect for --inventory before any display filter
                if args.INVENTORY:
                    inventory['physical_drive'].append(
                        dict(drive_data, system_ids=systems['Id'])
                    )
                # --match/--ignore: filter by item name
                item_name = drive_data['Name'] or drive_data.get('Id', '')
                if ignore_patterns and any(
                    p.search(item_name) for p in ignore_patterns
                ):
                    continue
                if match_patterns and not any(
                    p.search(item_name) for p in match_patterns
                ):
                    continue
                # is the storage_data state healthy at all?
                drive_data_state = lib.redfish.get_state(drive_data)
                state = lib.base.get_worst(state, drive_data_state)
                drive_data['State'] = lib.base.state2str(
                    drive_data_state, empty_ok=False
                )
                drive_count += 1
                if drive_data_state != STATE_OK:
                    drive_not_ok += 1
                # perfdata: remaining SSD/flash endurance as a 0-100% gauge so
                # the wear-out trend is graphable. This is a gauge, not a
                # monotonic counter, so it is safe to expose as perfdata.
                drive_id = (drive_data['Name'] or drive_data['Id']).replace(' ', '_')
                media_life = drive_data.get('PredictedMediaLifeLeftPercent')
                if isinstance(media_life, (int, float)):
                    perfdata += lib.base.get_perfdata(
                        f'{drive_id}_media_life_left',
                        media_life,
                        uom='%',
                        _min=0,
                        _max=100,
                    )
                # power-on hours is a monotonic counter, but there is no
                # meaningful gauge alternative for drive age, so it is exposed
                # as perfdata anyway.
                power_on_hours = drive_data.get('PowerOnHours')
                if isinstance(power_on_hours, (int, float)):
                    perfdata += lib.base.get_perfdata(
                        f'{drive_id}_power_on_hours',
                        power_on_hours,
                        _min=0,
                    )
                # drive temperature (degrees Celsius) is a gauge. Not every
                # vendor reports it, so it is only emitted when present.
                temperature = drive_data.get('Temperature')
                if isinstance(temperature, (int, float)):
                    perfdata += lib.base.get_perfdata(
                        f'{drive_id}_temperature',
                        temperature,
                        uom='Cel',
                    )
                table_data_drive.append(drive_data)

            # get volumes (logical drives) defined on the storage member
            volumes_link = storage_data.get('Volumes', {}).get('@odata.id')
            if volumes_link:
                # "/redfish/v1/Systems/437XR1138R2/Storage/RAID.SL.7-1/Volumes".
                # fetch_collection inlines the volume members in one request;
                # fetch_members fills in any left as bare references.
                volumes = lib.base.coe(
                    lib.redfish.fetch_collection(
                        lib.base.coe(lib.redfish.build_url(args.URL, volumes_link)),
                        expand=expand,
                        header=header,
                        insecure=args.INSECURE,
                        no_proxy=args.NO_PROXY,
                        proxy=args.PROXY,
                        timeout=args.TIMEOUT,
                        retries=args.RETRIES,
                        cache_expire=cache_expire,
                    )
                )
                volume_members = lib.base.coe(
                    lib.redfish.fetch_members(
                        volumes.get('Members', []),
                        args.URL,
                        header=header,
                        insecure=args.INSECURE,
                        no_proxy=args.NO_PROXY,
                        proxy=args.PROXY,
                        timeout=args.TIMEOUT,
                        retries=args.RETRIES,
                        cache_expire=cache_expire,
                    )
                )
                for volume_data in volume_members:
                    volume_data = lib.redfish.get_systems_storage_volumes(volume_data)
                    if volume_data['Status_State'] not in ['Enabled', 'Quiesced']:
                        continue
                    # collect for --inventory before any display filter
                    if args.INVENTORY:
                        inventory['logical_drive'].append(
                            dict(volume_data, system_ids=systems['Id'])
                        )
                    # --match/--ignore: filter by item name
                    item_name = volume_data['Name'] or volume_data.get('Id', '')
                    if ignore_patterns and any(
                        p.search(item_name) for p in ignore_patterns
                    ):
                        continue
                    if match_patterns and not any(
                        p.search(item_name) for p in match_patterns
                    ):
                        continue
                    # is the volume state healthy at all?
                    volume_data_state = lib.redfish.get_state(volume_data)
                    state = lib.base.get_worst(state, volume_data_state)
                    volume_data['State'] = lib.base.state2str(
                        volume_data_state, empty_ok=False
                    )
                    volume_count += 1
                    if volume_data_state != STATE_OK:
                        volume_not_ok += 1
                    table_data_volume.append(volume_data)

            storage_data = lib.redfish.get_systems_storage(storage_data)
            if storage_data['Status_State'] not in ['Enabled', 'Quiesced']:
                continue
            # collect for --inventory before any display filter
            if args.INVENTORY:
                inventory['storage_controller'].append(
                    dict(storage_data, system_ids=systems['Id'])
                )
            # --match/--ignore: filter by item name
            item_name = storage_data['Name'] or storage_data.get('Id', '')
            if ignore_patterns and any(p.search(item_name) for p in ignore_patterns):
                continue
            if match_patterns and not any(p.search(item_name) for p in match_patterns):
                continue
            # is the storage_data state healthy at all?
            storage_data_state = lib.redfish.get_state(storage_data)
            state = lib.base.get_worst(state, storage_data_state)
            storage_data['State'] = lib.base.state2str(
                storage_data_state, empty_ok=False
            )
            controller_count += 1
            if storage_data_state != STATE_OK:
                controller_not_ok += 1
            table_data.append(storage_data)

        if args.BRIEF:
            table_data_drive = [r for r in table_data_drive if r.get('State') != '[OK]']
        if table_data_drive:
            keys = [
                'Name',
                'MediaType',
                'Protocol',
                'Manufacturer',
                'Model',
                'SerialNumber',
                'CapacityBytes',
                'PredictedMediaLifeLeftPercent',
                'State',
            ]
            headers = [
                'Disk',
                'Type',
                'Proto',
                'Manufacturer',
                'Model',
                'SerialNumber',
                'Size',
                'LifeLeft %',
                'State',
            ]
            msg += '\n\n' + lib.base.get_table(table_data_drive, keys, header=headers)

        if args.BRIEF:
            table_data_volume = [
                r for r in table_data_volume if r.get('State') != '[OK]'
            ]
        if table_data_volume:
            keys = ['Name', 'RAIDType', 'CapacityBytes', 'Encrypted', 'State']
            headers = ['Volume', 'RAID', 'Size', 'Encrypted', 'State']
            msg += '\n\n' + lib.base.get_table(table_data_volume, keys, header=headers)

        if args.BRIEF:
            table_data = [r for r in table_data if r.get('State') != '[OK]']
        if table_data:
            keys = ['Id', 'Name', 'Description', 'Drives@odata.count', 'State']
            headers = ['ID', 'Name', 'Description', 'Drives', 'State']
            msg += '\n\n' + lib.base.get_table(table_data, keys, header=headers)

        msg += '\n\n'

    # --inventory: emit the collected components as JSON and exit before
    # building the human-readable message and perfdata
    if args.INVENTORY:
        print(json.dumps(inventory, ensure_ascii=False, indent=4, sort_keys=True))
        sys.exit(STATE_OK)

    # build the message
    members = lib.txt.pluralize('member', member_count)
    if state == STATE_CRIT:
        msg = (
            f'Checked storage on {member_count} {members}.'
            f' There are critical errors.\n\n'
        ) + msg
    elif state == STATE_WARN:
        msg = (
            f'Checked storage on {member_count} {members}. There are warnings.\n\n'
        ) + msg
    else:
        msg = (
            f'Everything is ok. Checked storage on {member_count} {members}.\n\n'
        ) + msg

    # perfdata: how many drives, volumes and storage controllers were checked
    # and how many are not OK. These are instantaneous gauges, not counters.
    perfdata += lib.base.get_perfdata(
        'drives',
        drive_count,
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'drives_not_ok',
        drive_not_ok,
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'volumes',
        volume_count,
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'volumes_not_ok',
        volume_not_ok,
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'storage_controllers',
        controller_count,
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'storage_controllers_not_ok',
        controller_not_ok,
        _min=0,
    )

    if args.VERBOSE:
        msg += '\n\n' + lib.redfish.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()
