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

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

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

DESCRIPTION = """Checks the System Event Log (SEL) of Redfish-compatible servers via the Redfish API.
Alerts based on the severity of log entries. Entries can be filtered by regex."""

API_BASE = '/redfish/v1'
DEFAULT_INSECURE = True
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 8
DEFAULT_URL = 'https://localhost:5000'


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(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    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(
        '--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. Default: %(default)s',
        dest='URL',
        default=DEFAULT_URL,
    )

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

    args, _ = parser.parse_known_args()
    return args


def load_test_fixture(test_args, path):
    # Replace the first element of args.TEST with the walk-specific
    # fixture path, read it via lib.lftest.test() and return the parsed
    # JSON. On a missing file or malformed JSON, exit STATE_UNKNOWN with
    # a helpful message instead of letting json.loads raise a traceback.
    if not os.path.isfile(path):
        lib.base.cu(f'Test fixture not found: "{path}".')
    test_args[0] = path
    stdout, _, _ = lib.lftest.test(test_args)
    try:
        return json.loads(stdout)
    except (json.JSONDecodeError, ValueError) as e:
        lib.base.cu(f'Test fixture "{path}" does not contain valid JSON: {e}')


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:
        if not args.URL.startswith('http'):
            lib.base.cu('--url parameter has to start with "http://" or https://".')
        header = {'Accept': 'application/json'}
        if args.USERNAME and args.PASSWORD:
            auth = f'{args.USERNAME}:{args.PASSWORD}'
            encoded_auth = lib.txt.to_text(base64.b64encode(lib.txt.to_bytes(auth)))
            header['Authorization'] = f'Basic {encoded_auth}'
        # service root: figure out the vendor to pick the entry point
        result = lib.base.coe(
            lib.url.fetch_json(
                f'{args.URL}{API_BASE}/',
                header=header,
                insecure=args.INSECURE,
                no_proxy=args.NO_PROXY,
                timeout=args.TIMEOUT,
            )
        )
        vendor = lib.redfish.get_vendor(result)
        entry_point = 'Systems' if vendor == 'supermicro' else 'Managers'
        # Entry point: the Managers (or Systems for Supermicro) collection
        result = lib.base.coe(
            lib.url.fetch_json(
                f'{args.URL}{API_BASE}/{entry_point}',
                header=header,
                insecure=args.INSECURE,
                no_proxy=args.NO_PROXY,
                timeout=args.TIMEOUT,
            )
        )
    else:
        # do not call the API, put in test data. Each API call in the
        # Redfish walk has an explicit fixture suffix, so the fixture
        # file names describe what they contain (root, managers, sel)
        # instead of being a string-appended chain.
        test_base = args.TEST[0]
        result = load_test_fixture(args.TEST, f'{test_base}-root')
        vendor = lib.redfish.get_vendor(result)
        result = load_test_fixture(args.TEST, f'{test_base}-managers')

    # "Members": [
    #     {
    #         "@odata.id": "/redfish/v1/Managers/BMC"
    #     }
    # ],
    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

    if vendor == 'generic':
        sel_path = '/LogServices/Log/Entries'
    elif vendor in ['avigilon']:  # which is a relabeled dell
        sel_path = '/LogServices'
    elif vendor in ['ami']:
        sel_path = '/LogServices/BIOS/Entries'
    elif vendor in ['cisco']:
        sel_path = '/LogServices/SEL/Entries'
    elif vendor in ['dell']:
        sel_path = '/LogServices/Sel/Entries'
    elif vendor in ['hpe', 'hp']:
        sel_path = '/LogServices/IML/Entries'
    elif vendor in ['lenovo']:
        sel_path = '/LogServices/ActiveLog/Entries'
    elif vendor in ['supermicro']:
        sel_path = '/LogServices/Log1/Entries'
    elif vendor in ['ts_fujitsu']:
        sel_path = '/LogServices/SystemEventLog/Entries'
    else:
        sel_path = ''

    # analyze data: follow each "Member" link and aggregate the SEL entries'
    # severity into `state`.
    for member in result.get('Members', []):
        if not sel_path:
            continue
        member_count += 1
        if args.TEST is None:
            # For example {https://localhost:5000} {/redfish/v1/Managers/BMC} {/LogServices/Log/Entries}
            sel = lib.base.coe(
                lib.url.fetch_json(
                    f'{args.URL}{member["@odata.id"]}{sel_path}',
                    header=header,
                    insecure=args.INSECURE,
                    no_proxy=args.NO_PROXY,
                    timeout=args.TIMEOUT,
                )
            )
        else:
            sel = load_test_fixture(args.TEST, f'{test_base}-sel')
        member_msg, member_state = lib.redfish.get_manager_logservices_sel_entries(sel)
        if member_msg:
            # build the message
            msg += f'{member["@odata.id"]}\n{member_msg}\n\n'
            state = lib.base.get_worst(state, member_state)

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

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


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