#!/bin/bash
# SPDX-License-Identifier: MIT
# ============================================================
# ITCheckAI OS Check Script - Linux
# Version    : 2.3.0
# Schema     : itcheck.linux.check/1
# Applies to : RHEL / CentOS / Rocky / AlmaLinux / Ubuntu / Debian /
#              SLES / openEuler / Anolis / Kylin / UOS and derivatives
# Usage      : sudo bash linux-check-v2.3.0.sh [--out-dir DIR] [--cmd-timeout SEC] [--perf-timeout SEC] [--skip-perf]
# Output     : /tmp/<hostname>.<serial>.check-<timestamp>.tar.gz
# Note       : Strictly read-only collection; records raw values & execution
#              metadata only (health thresholds stay on the server).
#              Detects virtualization/container context, NTP sync (chronyc/ntpstat),
#              kernel taint, FD usage, Tuned, NUMA, THP/HugePages, I/O schedulers,
#              NVMe SMART, FC HBA sysfs counters, kdump metadata, PSI pressure,
#              TCP state counts, AppArmor, whitelist-only sshd policy, UID=0/sudo
#              (never reads shadow passwords), /proc zombies, OpenSSH 9.8+
#              sshd-session auth-failure aggregates, hardware RAID & EDAC.
#              Restricts/redacts credential-bearing args, crontab, logs & Safe ID.
# ============================================================

set -u
umask 077

SCRIPT_NAME="linux-check"
SCRIPT_VERSION="2.3.0"
SCRIPT_FILE="linux-check-v2.3.0.sh"
SCHEMA_VERSION="itcheck.linux.check/1"

# Use C locale for consistent command output/error messages without altering host TZ.
LC_ALL=C
export LC_ALL

# Append sbin directories so non-root runs can still distinguish missing tools from permission denied.
if [ "${ITCHECK_KEEP_PATH:-0}" != "1" ]; then
    PATH="${PATH}:/usr/local/sbin:/usr/sbin:/sbin"
    export PATH
fi

OUT_DIR="${ITCHECK_OUT_DIR:-/tmp}"
CMD_TIMEOUT_SEC="${ITCHECK_CMD_TIMEOUT:-30}"
PERF_TIMEOUT_SEC="${ITCHECK_PERF_TIMEOUT:-60}"
MAX_ITEM_BYTES="${ITCHECK_MAX_ITEM_BYTES:-1048576}"
SKIP_PERF="${ITCHECK_SKIP_PERF:-0}"
ROOT_PREFIX="${ITCHECK_ROOT:-}"

usage() {
    cat <<'EOF'
Usage: linux-check-v2.3.0.sh [OPTIONS]

Read-only Linux check collector (schema: itcheck.linux.check/1).

Options:
  --out-dir DIR          Output directory for final .tar.gz (default: /tmp)
  --cmd-timeout SEC      Per-command timeout in seconds (default: 30)
  --perf-timeout SEC     Performance sampling command timeout in seconds (default: 60)
  --max-item-bytes N     Maximum bytes retained per collected item (default: 1048576)
  --skip-perf            Skip live vmstat/iostat/mpstat sampling (marks items as skipped)
  --version              Print script version and inner schema, then exit
  -h, --help             Show this help message and exit
EOF
}

is_pos_int() {
    case "$1" in
        ''|*[!0-9]*) return 1 ;;
        *) [ "$1" -ge 1 ] ;;
    esac
}

while [ $# -gt 0 ]; do
    case "$1" in
        --out-dir)
            [ $# -ge 2 ] || { echo "ERROR: --out-dir requires a value" >&2; exit 2; }
            OUT_DIR="$2"; shift 2 ;;
        --cmd-timeout)
            [ $# -ge 2 ] || { echo "ERROR: --cmd-timeout requires a value" >&2; exit 2; }
            CMD_TIMEOUT_SEC="$2"; shift 2 ;;
        --perf-timeout)
            [ $# -ge 2 ] || { echo "ERROR: --perf-timeout requires a value" >&2; exit 2; }
            PERF_TIMEOUT_SEC="$2"; shift 2 ;;
        --max-item-bytes)
            [ $# -ge 2 ] || { echo "ERROR: --max-item-bytes requires a value" >&2; exit 2; }
            MAX_ITEM_BYTES="$2"; shift 2 ;;
        --skip-perf)
            SKIP_PERF=1; shift ;;
        --version)
            printf '%s %s (schema: %s)\n' "$SCRIPT_NAME" "$SCRIPT_VERSION" "$SCHEMA_VERSION"
            exit 0 ;;
        -h|--help)
            usage; exit 0 ;;
        *)
            echo "ERROR: unknown option: $1" >&2
            usage >&2
            exit 2 ;;
    esac
done

is_pos_int "$CMD_TIMEOUT_SEC" || { echo "ERROR: invalid --cmd-timeout: $CMD_TIMEOUT_SEC" >&2; exit 2; }
is_pos_int "$PERF_TIMEOUT_SEC" || { echo "ERROR: invalid --perf-timeout: $PERF_TIMEOUT_SEC" >&2; exit 2; }
is_pos_int "$MAX_ITEM_BYTES" || { echo "ERROR: invalid --max-item-bytes: $MAX_ITEM_BYTES" >&2; exit 2; }

OUT_DIR="${OUT_DIR%/}"
[ -z "$OUT_DIR" ] && OUT_DIR="/"
[ -d "$OUT_DIR" ] || mkdir -p "$OUT_DIR" || { echo "ERROR: cannot access output dir $OUT_DIR" >&2; exit 1; }
OUT_DIR=$(cd "$OUT_DIR" 2>/dev/null && pwd) || { echo "ERROR: cannot access output dir $OUT_DIR" >&2; exit 1; }

# ── Helpers: timestamps, monotonic ms, sha256, JSON escaping, safe tokens ──

iso_now_raw() {
    local raw tz
    raw=$(date +%Y-%m-%dT%H:%M:%S%z 2>/dev/null || echo "")
    if [ "${#raw}" -ge 24 ]; then
        tz="${raw: -5}"
        case "$tz" in
            [+-][0-9][0-9][0-9][0-9])
                printf '%s%s:%s' "${raw%?????}" "${tz%??}" "${tz#???}"
                return 0 ;;
        esac
    fi
    date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo "1970-01-01T00:00:00Z"
}

now_ms() {
    local t
    t=$(date +%s%3N 2>/dev/null || echo "")
    case "$t" in
        ''|*[!0-9]*)
            if [ -r /proc/uptime ]; then
                awk '{ printf "%.0f", $1 * 1000 }' /proc/uptime 2>/dev/null && return 0
            fi
            t=$(date +%s 2>/dev/null || echo 0)
            case "$t" in
                ''|*[!0-9]*) echo 0 ;;
                *) echo "$((t * 1000))" ;;
            esac ;;
        *)
            echo "$t" ;;
    esac
}

calc_sha256() {
    local f="$1"
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$f" 2>/dev/null | awk '{print tolower($1)}'
    elif command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$f" 2>/dev/null | awk '{print tolower($1)}'
    elif command -v openssl >/dev/null 2>&1; then
        openssl dgst -sha256 "$f" 2>/dev/null | awk '{print tolower($NF)}'
    else
        echo ""
    fi
}

file_size_bytes() {
    wc -c < "$1" 2>/dev/null | tr -d '[:space:]'
}

json_escape() {
    awk 'BEGIN {
        for (i = 0; i < 32; i++) {
            c = sprintf("%c", i)
            ctrl[c] = sprintf("\\u%04x", i)
        }
        ctrl["\b"] = "\\b"
        ctrl["\f"] = "\\f"
        ctrl["\n"] = "\\n"
        ctrl["\r"] = "\\r"
        ctrl["\t"] = "\\t"
    }
    {
        if (NR > 1) out = out "\\n"
        line = $0
        n = length(line)
        for (i = 1; i <= n; i++) {
            ch = substr(line, i, 1)
            if (ch == "\\") out = out "\\\\"
            else if (ch == "\"") out = out "\\\""
            else if (ch in ctrl) out = out ctrl[ch]
            else out = out ch
        }
    }
    END { printf "\"%s\"", out }'
}

sanitize_token() {
    local s
    s=$(printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_' | sed 's/^\.*//')
    [ -z "$s" ] && s="unknown"
    printf '%s' "$s"
}

sanitize_id_part() {
    local s
    s=$(printf '%s' "$1" | tr 'A-Z' 'a-z' | tr -c 'a-z0-9_-' '_' | sed 's/^_*//; s/_*$//')
    [ -z "$s" ] && s="item"
    printf '%s' "$s"
}

# Detect portable timeout mechanism once.
TIMEOUT_MODE="bash"
if command -v timeout >/dev/null 2>&1; then
    if timeout -k 2 1 true >/dev/null 2>&1; then
        TIMEOUT_MODE="gnu_k"
    elif timeout 1 true >/dev/null 2>&1; then
        TIMEOUT_MODE="basic"
    fi
fi

# exec_with_timeout <sec> <raw_out_file> <cmd...>
# Runs command directly with timeout, captures combined stdout+stderr to raw_out_file,
# and returns the exact exit code (124/137 on timeout).
exec_with_timeout() {
    local t_sec="$1"
    local raw_out="$2"
    shift 2
    local rc=0
    case "$TIMEOUT_MODE" in
        gnu_k)
            timeout -k 5 "$t_sec" "$@" >"$raw_out" 2>&1
            rc=$? ;;
        basic)
            timeout "$t_sec" "$@" >"$raw_out" 2>&1
            rc=$? ;;
        *)
            "$@" >"$raw_out" 2>&1 &
            local cmd_pid=$!
            (
                sleep "$t_sec"
                kill -TERM "$cmd_pid" 2>/dev/null || true
                sleep 2
                kill -KILL "$cmd_pid" 2>/dev/null || true
            ) >/dev/null 2>&1 &
            local wd_pid=$!
            wait "$cmd_pid" 2>/dev/null
            rc=$?
            kill "$wd_pid" 2>/dev/null || true
            wait "$wd_pid" 2>/dev/null || true
            if [ "$rc" -eq 143 ] || [ "$rc" -eq 137 ]; then
                rc=124
            fi ;;
    esac
    return "$rc"
}

# exec_with_timeout_split <sec> <stdout_file> <stderr_file> <cmd...>
# Like exec_with_timeout, but separates stdout and stderr so benign stderr warnings
# (e.g. lspci pcilib: sysfs_read_vpd) do not corrupt structured stdout when rc == 0.
exec_with_timeout_split() {
    local t_sec="$1"
    local std_out="$2"
    local std_err="$3"
    shift 3
    local rc=0
    case "$TIMEOUT_MODE" in
        gnu_k)
            timeout -k 5 "$t_sec" "$@" >"$std_out" 2>"$std_err"
            rc=$? ;;
        basic)
            timeout "$t_sec" "$@" >"$std_out" 2>"$std_err"
            rc=$? ;;
        *)
            "$@" >"$std_out" 2>"$std_err" &
            local cmd_pid=$!
            (
                sleep "$t_sec"
                kill -TERM "$cmd_pid" 2>/dev/null || true
                sleep 2
                kill -KILL "$cmd_pid" 2>/dev/null || true
            ) >/dev/null 2>&1 &
            local wd_pid=$!
            wait "$cmd_pid" 2>/dev/null
            rc=$?
            kill "$wd_pid" 2>/dev/null || true
            wait "$wd_pid" 2>/dev/null || true
            if [ "$rc" -eq 143 ] || [ "$rc" -eq 137 ]; then
                rc=124
            fi ;;
    esac
    return "$rc"
}

# Strictly POSIX awk stream redactor (no GNU-only extensions or {m,n} intervals):
# masks PEM keys, URL passwords, Authorization/Cookie headers, Bearer/JWT/cloud tokens,
# CLI password flags, and sensitive key=value / key:value pairs.
# Writes redacted text to $2 and writes "1" or "0" to $3 indicating whether any line was redacted.
redact_file() {
    local src="$1"
    local dst="$2"
    local flag_file="$3"
    awk -v flag_file="$flag_file" '
    function is_safe_placeholder(val,   lv) {
        lv = tolower(val)
        return (lv == "" || lv == "<empty>" || lv == "none" || lv == "null" || lv == "true" || lv == "false" || lv == "[redacted]" || lv ~ /^\*+$/)
    }
    function mask_urls(s,   out, rest, scheme_end, userinfo, colon_pos, user_part, pass_part) {
        out = ""
        rest = s
        while (match(rest, /[A-Za-z][A-Za-z0-9+.-]*:\/\//)) {
            scheme_end = RSTART + RLENGTH - 1
            out = out substr(rest, 1, scheme_end)
            rest = substr(rest, scheme_end + 1)
            if (match(rest, /^[^[:space:]"'\'';,<>\/]+@/)) {
                userinfo = substr(rest, 1, RLENGTH - 1)
                colon_pos = index(userinfo, ":")
                if (colon_pos > 0) {
                    user_part = substr(userinfo, 1, colon_pos - 1)
                    pass_part = substr(userinfo, colon_pos + 1)
                    if (!is_safe_placeholder(pass_part)) {
                        out = out user_part ":[REDACTED]@"
                        rest = substr(rest, RLENGTH + 1)
                        changed = 1
                        continue
                    }
                }
            }
        }
        return out rest
    }
    function mask_prefixed_token(s, re, min_len, label,   out, rest, tok) {
        out = ""
        rest = s
        while (match(rest, re)) {
            tok = substr(rest, RSTART, RLENGTH)
            if (RLENGTH >= min_len) {
                out = out substr(rest, 1, RSTART - 1) label
                rest = substr(rest, RSTART + RLENGTH)
                changed = 1
            } else {
                out = out substr(rest, 1, RSTART + RLENGTH - 1)
                rest = substr(rest, RSTART + RLENGTH)
            }
        }
        return out rest
    }
    function mask_headers_and_tokens(s,   low, out, rest, head, tail, tok, lead) {
        # Authorization / Proxy-Authorization headers
        low = tolower(s)
        if (match(low, /(proxy-)?authorization[[:space:]]*:[[:space:]]*(bearer|basic|token|digest|aws4-hmac-sha256)[[:space:]]+/)) {
            head = substr(s, 1, RSTART + RLENGTH - 1)
            tail = substr(s, RSTART + RLENGTH)
            if (match(tail, /^[^[:space:]"'\'';,}]+/)) {
                if (!is_safe_placeholder(substr(tail, 1, RLENGTH))) {
                    s = head "[REDACTED]" substr(tail, RLENGTH + 1)
                    changed = 1
                }
            }
        }
        # Cookie / Set-Cookie / X-Auth-Token / X-API-Key / X-Access-Token headers
        low = tolower(s)
        if (match(low, /(^|[^a-z0-9_-])(set-cookie|cookie|x-auth-token|x-api-key|x-api-token|x-access-token)[[:space:]]*:[[:space:]]*/)) {
            head = substr(s, 1, RSTART + RLENGTH - 1)
            tail = substr(s, RSTART + RLENGTH)
            if (!is_safe_placeholder(tail)) {
                s = head "[REDACTED]"
                changed = 1
            }
        }
        # Standalone Bearer tokens
        out = ""
        rest = s
        while (match(tolower(rest), /(^|[^a-z0-9_])bearer[[:space:]]+/)) {
            head = substr(rest, 1, RSTART + RLENGTH - 1)
            tail = substr(rest, RSTART + RLENGTH)
            if (match(tail, /^[A-Za-z0-9._~+\/=-]+/) && RLENGTH >= 6) {
                if (!is_safe_placeholder(substr(tail, 1, RLENGTH))) {
                    out = out head "[REDACTED]"
                    rest = substr(tail, RLENGTH + 1)
                    changed = 1
                    continue
                }
            }
            out = out head
            rest = tail
        }
        s = out rest
        # JWT tokens (three base64url segments starting with eyJ)
        s = mask_prefixed_token(s, "eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+", 24, "[REDACTED:JWT]")
        # Cloud / VCS / API token prefixes
        s = mask_prefixed_token(s, "(AKIA|ASIA)[0-9A-Z]+", 20, "[REDACTED:TOKEN]")
        s = mask_prefixed_token(s, "gh[pousr]_[A-Za-z0-9_]+", 20, "[REDACTED:TOKEN]")
        s = mask_prefixed_token(s, "glpat-[A-Za-z0-9_-]+", 22, "[REDACTED:TOKEN]")
        out = ""
        rest = s
        while (match(rest, /(^|[^A-Za-z0-9_-])(sk-|xox[baprs]-)[A-Za-z0-9_-]+/)) {
            tok = substr(rest, RSTART, RLENGTH)
            lead = ""
            if (substr(tok, 1, 1) !~ /^[A-Za-z0-9_-]$/) {
                lead = substr(tok, 1, 1)
                tok = substr(tok, 2)
            }
            if (length(tok) >= 17) {
                out = out substr(rest, 1, RSTART - 1) lead "[REDACTED:TOKEN]"
                rest = substr(rest, RSTART + RLENGTH)
                changed = 1
            } else {
                out = out substr(rest, 1, RSTART + RLENGTH - 1)
                rest = substr(rest, RSTART + RLENGTH)
            }
        }
        return out rest
    }
    function mask_cli_flags(s,   out, rest, head, tail, val, qch, low, tok, flg, m_start, m_len, after_tok) {
        # Long flags: --password=val, --password val, --token=val, etc.
        out = ""
        rest = s
        while (match(tolower(rest), /(^|[[:space:]])--?(password|passwd|pass|pwd|secret|token|api[-_]?key|access[-_]?key|auth[-_]?token|private[-_]?key|client[-_]?secret|passphrase|snmp[-_]?community|community)([=]|[[:space:]]+)/)) {
            head = substr(rest, 1, RSTART + RLENGTH - 1)
            tail = substr(rest, RSTART + RLENGTH)
            if (substr(tail, 1, 1) == "\"" || substr(tail, 1, 1) == "'"'"'") {
                qch = substr(tail, 1, 1)
                if (match(substr(tail, 2), qch == "\"" ? /^[^"]*"/ : /^[^'"'"']*'"'"'/)) {
                    val = substr(tail, 2, RLENGTH - 1)
                    if (!is_safe_placeholder(val)) {
                        out = out head qch "[REDACTED]" qch
                        rest = substr(tail, 2 + RLENGTH)
                        changed = 1
                        continue
                    }
                }
            } else if (match(tail, /^[^[:space:]"'\'';,)}]+/)) {
                val = substr(tail, 1, RLENGTH)
                if (!is_safe_placeholder(val)) {
                    out = out head "[REDACTED]"
                    rest = substr(tail, RLENGTH + 1)
                    changed = 1
                    continue
                }
            }
            out = out head
            rest = tail
        }
        s = out rest
        # Tool-specific short password flags: mysql -pSECRET, sshpass -p SECRET, redis-cli -a SECRET, ipmitool -P SECRET, curl -u user:pass
        low = tolower(s)
        if (low ~ /(mysql|mysqldump|mysqladmin|sshpass|redis-cli|ipmitool|curl|wget)/) {
            out = ""
            rest = s
            while (match(rest, /(^|[[:space:]])(-p|-P|-a|-u|--user)([[:space:]]+|[^[:space:]"'\'';,]+)/)) {
                m_start = RSTART
                m_len = RLENGTH
                head = substr(rest, 1, m_start - 1)
                tok = substr(rest, m_start, m_len)
                after_tok = substr(rest, m_start + m_len)
                if (match(tok, /^[[:space:]]*(-p|-P|-a|-u|--user)[[:space:]]+/)) {
                    flg = substr(tok, 1, RLENGTH)
                    if (match(after_tok, /^[^[:space:]"'\'';,]+/)) {
                        val = substr(after_tok, 1, RLENGTH)
                        if (!is_safe_placeholder(val) && substr(val, 1, 1) != "-") {
                            out = out head flg "[REDACTED]"
                            rest = substr(after_tok, RLENGTH + 1)
                            changed = 1
                            continue
                        }
                    }
                } else if (match(tok, /^[[:space:]]*(-p|-P|-a)/)) {
                    flg = substr(tok, 1, RLENGTH)
                    val = substr(tok, RLENGTH + 1)
                    if (!is_safe_placeholder(val)) {
                        out = out head flg "[REDACTED]"
                        rest = after_tok
                        changed = 1
                        continue
                    }
                }
                out = out head tok
                rest = after_tok
            }
            s = out rest
        }
        return s
    }
    function mask_kv_secrets(s,   out, rest, head, tail, val, qch) {
        out = ""
        rest = s
        while (match(tolower(rest), /(^|[^a-z0-9_])([a-z0-9_.-]*[_.-])?(password|passwd|pass|pwd|secret|secret_key|secretkey|access_key|access_key_id|secret_access_key|api_key|apikey|api_token|auth_token|bearer_token|private_key|client_secret|refresh_token|session_token|token|passphrase|snmp_community|community_string|chap_password|password_in|mysql_pwd|pgpassword|aws_secret_access_key|luks\.key|luks_key|credentials_password|credential)["'\'']*[[:space:]]*(=|:)[[:space:]]*/)) {
            head = substr(rest, 1, RSTART + RLENGTH - 1)
            tail = substr(rest, RSTART + RLENGTH)
            if (substr(tail, 1, 1) == "\"" || substr(tail, 1, 1) == "'"'"'") {
                qch = substr(tail, 1, 1)
                if (match(substr(tail, 2), qch == "\"" ? /^[^"]*"/ : /^[^'"'"']*'"'"'/)) {
                    val = substr(tail, 2, RLENGTH - 1)
                    if (!is_safe_placeholder(val)) {
                        out = out head qch "[REDACTED]" qch
                        rest = substr(tail, 2 + RLENGTH)
                        changed = 1
                        continue
                    }
                }
            } else if (match(tail, /^[^[:space:]"'\'';,)}]+/)) {
                val = substr(tail, 1, RLENGTH)
                if (!is_safe_placeholder(val)) {
                    out = out head "[REDACTED]"
                    rest = substr(tail, RLENGTH + 1)
                    changed = 1
                    continue
                }
            }
            out = out head
            rest = tail
        }
        return out rest
    }
    BEGIN {
        in_key = 0
        changed = 0
    }
    {
        line = $0
        if (in_key) {
            if (line ~ /-----END [A-Za-z0-9 ]*PRIVATE KEY( BLOCK)?-----/) {
                in_key = 0
            }
            next
        }
        if (line ~ /-----BEGIN [A-Za-z0-9 ]*PRIVATE KEY( BLOCK)?-----/) {
            in_key = 1
            changed = 1
            print "[REDACTED:PRIVATE_KEY]"
            next
        }
        # Mask RAID controller Safe ID (Broadcom/LSI advanced feature activation identifier)
        if (match(tolower(line), /^[[:space:]]*safe[[:space:]]+id[[:space:]]*=[[:space:]]*/)) {
            val_safe = substr(line, RSTART + RLENGTH)
            sub(/[[:space:]]+$/, "", val_safe)
            if (!is_safe_placeholder(val_safe)) {
                line = substr(line, 1, RSTART + RLENGTH - 1) "[REDACTED]"
                changed = 1
            }
        }
        line = mask_urls(line)
        line = mask_headers_and_tokens(line)
        line = mask_cli_flags(line)
        line = mask_kv_secrets(line)
        print line
    }
    END {
        printf "%d\n", changed > flag_file
    }' "$src" > "$dst"
}

is_permission_error_text() {
    local f="$1"
    grep -qiE 'permission denied|operation not permitted|must be root|must be run as root|not superuser|insufficient permissions|you must be root|access denied|requires root|can'\''t open .*: permission denied' "$f" 2>/dev/null
}

# ── Host Identity & Start Metadata ──

START_ISO=$(iso_now_raw)
START_MS=$(now_ms)
DATE_RAW=$(date 2>/dev/null || echo "$START_ISO")
TZ_RAW=$(date '+%Z %z' 2>/dev/null || echo "")
STAMP=$(date +%Y%m%d_%H%M%S 2>/dev/null || echo "19700101_000000")

RUN_AS_UID=$(id -u 2>/dev/null || echo 65534)
case "$RUN_AS_UID" in ''|*[!0-9]*) RUN_AS_UID=65534 ;; esac
RUN_AS_USER=$(id -un 2>/dev/null || echo unknown)
if [ "$RUN_AS_UID" -eq 0 ]; then
    IS_ROOT="true"
    if [ -n "${SUDO_USER:-}" ]; then
        PRIVILEGE_MODE="sudo"
    else
        PRIVILEGE_MODE="root"
    fi
else
    IS_ROOT="false"
    PRIVILEGE_MODE="non_root"
fi

HOSTNAME_RAW=$(hostname 2>/dev/null || echo unknown)
[ -z "$HOSTNAME_RAW" ] && HOSTNAME_RAW="unknown"
HOSTNAME_SAFE=$(sanitize_token "$HOSTNAME_RAW")

SERIAL_RAW=""
SERIAL_SOURCE="unavailable"
if command -v dmidecode >/dev/null 2>&1; then
    SERIAL_RAW=$(dmidecode -s system-serial-number 2>/dev/null | grep -v '^#' | head -n 1 | tr -d ' /')
    if [ -n "$SERIAL_RAW" ]; then
        SERIAL_SOURCE="dmidecode"
    fi
fi
if [ -z "$SERIAL_RAW" ] && [ -r "${ROOT_PREFIX}/sys/class/dmi/id/product_serial" ]; then
    SERIAL_RAW=$(cat "${ROOT_PREFIX}/sys/class/dmi/id/product_serial" 2>/dev/null | head -n 1 | tr -d ' /')
    if [ -n "$SERIAL_RAW" ]; then
        SERIAL_SOURCE="sysfs"
    fi
fi
SERIAL_FOR_NAME="$SERIAL_RAW"
[ -z "$SERIAL_FOR_NAME" ] && SERIAL_FOR_NAME="NotAvailable"
SERIAL_FOR_NAME=$(sanitize_token "$SERIAL_FOR_NAME")

OS_ID=""
OS_PRETTY_NAME=""
if [ -r "${ROOT_PREFIX}/etc/os-release" ]; then
    OS_ID=$(awk -F= '$1=="ID"{gsub(/^"|"$/,"",$2); print $2; exit}' "${ROOT_PREFIX}/etc/os-release" 2>/dev/null || echo "")
    OS_PRETTY_NAME=$(awk -F= '$1=="PRETTY_NAME"{gsub(/^"|"$/,"",$2); print $2; exit}' "${ROOT_PREFIX}/etc/os-release" 2>/dev/null || echo "")
fi
KERNEL_REL=$(uname -r 2>/dev/null || echo "")
ARCH_STR=$(uname -m 2>/dev/null || echo "")

SCRIPT_SELF_SHA256=""
if [ -n "${BASH_SOURCE[0]:-}" ] && [ -f "${BASH_SOURCE[0]}" ]; then
    SCRIPT_SELF_SHA256=$(calc_sha256 "${BASH_SOURCE[0]}")
fi

DIRNAME="${HOSTNAME_SAFE}.${SERIAL_FOR_NAME}.check-${STAMP}"
CFGDIR="${OUT_DIR}/${DIRNAME}"
SCRATCH_DIR=$(mktemp -d "${OUT_DIR}/.itcheck-work.XXXXXX" 2>/dev/null || mktemp -d "/tmp/.itcheck-work.XXXXXX")
ITEMS_JSONL="${SCRATCH_DIR}/items.jsonl"
WARNINGS_TXT="${SCRATCH_DIR}/warnings.txt"
: > "$ITEMS_JSONL"
: > "$WARNINGS_TXT"

cleanup_scratch() {
    rm -rf "$SCRATCH_DIR" 2>/dev/null || true
}
trap cleanup_scratch EXIT

mkdir -p "$CFGDIR" || { echo "ERROR: cannot create working dir $CFGDIR" >&2; exit 1; }
printf '%s\n' "$DATE_RAW" > "$CFGDIR/date.log"

add_warning() {
    printf '%s\n' "$1" >> "$WARNINGS_TXT"
}

if [ "$IS_ROOT" != "true" ]; then
    NON_ROOT_WARN="WARNING: not running as root, some hardware/log data will be incomplete."
    echo "$NON_ROOT_WARN" | tee "$CFGDIR/warning.txt"
    add_warning "$NON_ROOT_WARN"
fi

# Counters for collection.counts
CNT_TOTAL=0
CNT_OK=0
CNT_EMPTY=0
CNT_PERM=0
CNT_MISSING=0
CNT_TIMEOUT=0
CNT_FAILED=0
CNT_NA=0
CNT_SKIPPED=0

bump_status_count() {
    CNT_TOTAL=$((CNT_TOTAL + 1))
    case "$1" in
        ok) CNT_OK=$((CNT_OK + 1)) ;;
        empty) CNT_EMPTY=$((CNT_EMPTY + 1)) ;;
        permission_denied) CNT_PERM=$((CNT_PERM + 1)) ;;
        command_missing) CNT_MISSING=$((CNT_MISSING + 1)) ;;
        timeout) CNT_TIMEOUT=$((CNT_TIMEOUT + 1)) ;;
        failed) CNT_FAILED=$((CNT_FAILED + 1)) ;;
        not_applicable) CNT_NA=$((CNT_NA + 1)) ;;
        skipped) CNT_SKIPPED=$((CNT_SKIPPED + 1)) ;;
    esac
}

# finalize_item writes the final section file (with optional redaction & truncation),
# calculates exact byte size & SHA-256, and appends one JSON object line to ITEMS_JSONL.
finalize_item() {
    local item_id="$1"
    local section="$2"
    local rel_path="$3"
    local src_kind="$4"
    local src_cmd="$5"
    local src_origin="$6"
    local target="$7"
    local req_root="$8"
    local item_start_iso="$9"
    local item_start_ms="${10}"
    local exit_code="${11}"
    local status="${12}"
    local timeout_sec="${13}"
    local do_redact="${14}"
    local force_redacted="${15}"
    local body_file="${16}"
    local note="${17}"

    local out_path="${CFGDIR}/${rel_path}"
    mkdir -p "$(dirname "$out_path")"

    local work_body="${SCRATCH_DIR}/work_body.tmp"
    local redacted_flag="${SCRATCH_DIR}/redacted.flag"
    local redacted="false"
    local truncated="false"

    if [ "$do_redact" = "true" ] && [ -s "$body_file" ]; then
        redact_file "$body_file" "$work_body" "$redacted_flag"
        if [ "$(cat "$redacted_flag" 2>/dev/null || echo 0)" = "1" ]; then
            redacted="true"
        fi
    else
        cp "$body_file" "$work_body" 2>/dev/null || : > "$work_body"
    fi
    if [ "$force_redacted" = "true" ]; then
        redacted="true"
    fi

    local body_bytes
    body_bytes=$(file_size_bytes "$work_body")
    if [ "${body_bytes:-0}" -gt "$MAX_ITEM_BYTES" ]; then
        head -c "$MAX_ITEM_BYTES" "$work_body" > "${SCRATCH_DIR}/trunc.tmp"
        printf '\n[output truncated at %s bytes]\n' "$MAX_ITEM_BYTES" >> "${SCRATCH_DIR}/trunc.tmp"
        mv "${SCRATCH_DIR}/trunc.tmp" "$work_body"
        truncated="true"
    fi

    {
        printf '### %s\n' "$src_cmd"
        if [ -s "$work_body" ]; then
            cat "$work_body"
            printf '\n'
        fi
        case "$status" in
            command_missing)
                printf '[command missing: %s]\n' "${note:-$src_cmd}" ;;
            permission_denied)
                printf '[permission denied: %s]\n' "${note:-requires root privileges}" ;;
            timeout)
                printf '[command timed out after %ss]\n' "$timeout_sec" ;;
            not_applicable)
                printf '[not applicable: %s]\n' "${note:-resource not present}" ;;
            skipped)
                printf '[skipped: %s]\n' "${note:-skipped by option}" ;;
            failed)
                printf '[command failed with exit code %s]\n' "$exit_code" ;;
        esac
    } > "$out_path"

    local item_end_iso item_end_ms dur_ms final_size final_sha
    item_end_iso=$(iso_now_raw)
    item_end_ms=$(now_ms)
    dur_ms=$((item_end_ms - item_start_ms))
    [ "$dur_ms" -lt 0 ] && dur_ms=0

    final_size=$(file_size_bytes "$out_path")
    [ -z "$final_size" ] && final_size=0
    final_sha=$(calc_sha256 "$out_path")

    bump_status_count "$status"

    local j_id j_sec j_path j_kind j_cmd j_origin j_target j_start j_end j_status j_sha j_note
    j_id=$(printf '%s' "$item_id" | json_escape)
    j_sec=$(printf '%s' "$section" | json_escape)
    j_path=$(printf '%s' "$rel_path" | json_escape)
    j_kind=$(printf '%s' "$src_kind" | json_escape)
    j_cmd=$(printf '%s' "$src_cmd" | json_escape)
    j_origin=$(printf '%s' "$src_origin" | json_escape)
    j_target=$(printf '%s' "$target" | json_escape)
    j_start=$(printf '%s' "$item_start_iso" | json_escape)
    j_end=$(printf '%s' "$item_end_iso" | json_escape)
    j_status=$(printf '%s' "$status" | json_escape)
    j_sha=$(printf '%s' "$final_sha" | json_escape)
    j_note=$(printf '%s' "$note" | json_escape)

    local src_json
    if [ -n "$src_origin" ]; then
        src_json="{\"kind\":${j_kind},\"command\":${j_cmd},\"origin\":${j_origin}}"
    else
        src_json="{\"kind\":${j_kind},\"command\":${j_cmd}}"
    fi

    local opt_fields=""
    if [ -n "$target" ]; then
        opt_fields="${opt_fields},\"target\":${j_target}"
    fi
    if [ -n "$note" ]; then
        opt_fields="${opt_fields},\"note\":${j_note}"
    fi

    printf '{"id":%s,"section":%s,"path":%s,"source":%s%s,"requires_root":%s,"started_at_raw":%s,"finished_at_raw":%s,"duration_ms":%s,"exit_code":%s,"status":%s,"timeout_sec":%s,"truncated":%s,"redacted":%s,"size_bytes":%s,"sha256":%s}\n' \
        "$j_id" "$j_sec" "$j_path" "$src_json" "$opt_fields" "$req_root" \
        "$j_start" "$j_end" "$dur_ms" "$exit_code" "$j_status" "$timeout_sec" \
        "$truncated" "$redacted" "$final_size" "$j_sha" >> "$ITEMS_JSONL"
}

# classify_cmd_status <exit_code> <requires_root> <timeout_sec> <raw_out> [smart_mode] [elapsed_ms]
classify_cmd_status() {
    local rc="$1"
    local req_root="$2"
    local t_sec="$3"
    local raw_out="$4"
    local smart_mode="${5:-0}"
    local elapsed_ms="${6:-0}"

    if [ "$rc" -eq 124 ]; then
        echo "timeout"
        return 0
    fi
    if [ "$rc" -eq 137 ] && [ "$t_sec" -gt 0 ] && [ "$elapsed_ms" -ge $((t_sec * 1000 - 250)) ]; then
        echo "timeout"
        return 0
    fi
    if [ "$rc" -eq 127 ]; then
        echo "command_missing"
        return 0
    fi
    # smartctl exit code is a bitmask: low 3 bits (0..2 = value 7) indicate CLI/open/SMART cmd error;
    # bits 3..7 indicate SMART disk health/log flags while valid output was still collected.
    if [ "$smart_mode" = "1" ] && [ "$rc" -ne 0 ]; then
        if [ $((rc & 7)) -eq 0 ] && [ -s "$raw_out" ]; then
            echo "ok"
            return 0
        fi
    fi
    if [ "$rc" -eq 0 ]; then
        if [ "$IS_ROOT" != "true" ]; then
            if grep -qiE 'No journal files were opened due to insufficient permissions|You are currently not seeing messages from other users and the system' "$raw_out" 2>/dev/null; then
                if ! grep -viE '^(Hint:|      |-- No entries --|No journal files were opened)' "$raw_out" 2>/dev/null | grep -q '[^[:space:]]'; then
                    echo "permission_denied"
                    return 0
                fi
            fi
            if [ "$req_root" = "true" ] && is_permission_error_text "$raw_out"; then
                if ! grep -viE 'permission denied|operation not permitted|must be root|not superuser|insufficient permissions' "$raw_out" 2>/dev/null | grep -q '[^[:space:]]'; then
                    echo "permission_denied"
                    return 0
                fi
            fi
        fi
        if [ -s "$raw_out" ] && grep -q '[^[:space:]]' "$raw_out" 2>/dev/null; then
            echo "ok"
        else
            echo "empty"
        fi
        return 0
    fi
    if [ "$IS_ROOT" != "true" ]; then
        if [ "$req_root" = "true" ] || is_permission_error_text "$raw_out"; then
            echo "permission_denied"
            return 0
        fi
    fi
    echo "failed"
}

# run_cmd <id> <section> <rel_path> <src_kind> <req_root> <timeout_sec> <do_redact> <post_filter> <target> <display_cmd> -- <argv...>
# post_filter: none | head:N | tail:N | smart
run_cmd() {
    local item_id="$1" section="$2" rel_path="$3" src_kind="$4" req_root="$5"
    local t_sec="$6" do_redact="$7" post_filter="$8" target="$9" display_cmd="${10}"
    shift 10
    [ "${1:-}" = "--" ] && shift

    local bin="$1"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/cmd_raw.tmp"
    local filtered_out="${SCRATCH_DIR}/cmd_filtered.tmp"
    : > "$raw_out"
    : > "$filtered_out"

    if ! command -v "$bin" >/dev/null 2>&1; then
        finalize_item "$item_id" "$section" "$rel_path" "$src_kind" "$display_cmd" "$bin" "$target" \
            "$req_root" "$item_start_iso" "$item_start_ms" 127 "command_missing" "$t_sec" \
            "false" "false" "$filtered_out" "command not found: $bin"
        return 0
    fi

    local rc=0
    exec_with_timeout "$t_sec" "$raw_out" "$@" || rc=$?
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0

    local smart_mode=0
    [ "$post_filter" = "smart" ] && smart_mode=1
    local status
    status=$(classify_cmd_status "$rc" "$req_root" "$t_sec" "$raw_out" "$smart_mode" "$elapsed_ms")
    local note=""
    case "$status" in
        permission_denied) note="requires root privileges (uid=${RUN_AS_UID})" ;;
        timeout) note="timed out after ${t_sec}s" ;;
    esac

    case "$post_filter" in
        head:*)
            head -n "${post_filter#head:}" "$raw_out" > "$filtered_out" ;;
        tail:*)
            tail -n "${post_filter#tail:}" "$raw_out" > "$filtered_out" ;;
        *)
            cp "$raw_out" "$filtered_out" ;;
    esac

    finalize_item "$item_id" "$section" "$rel_path" "$src_kind" "$display_cmd" "$bin" "$target" \
        "$req_root" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$t_sec" \
        "$do_redact" "false" "$filtered_out" "$note"
}

# run_file <id> <section> <rel_path> <src_kind> <logical_path> <req_root> <do_redact> <tail_lines>
run_file() {
    local item_id="$1" section="$2" rel_path="$3" src_kind="$4" logical_path="$5"
    local req_root="$6" do_redact="$7" tail_lines="${8:-0}"

    local real_path="${ROOT_PREFIX}${logical_path}"
    local display_cmd
    if [ "$tail_lines" -gt 0 ]; then
        display_cmd="tail -n ${tail_lines} ${logical_path}"
    else
        display_cmd="cat ${logical_path}"
    fi

    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/file_raw.tmp"
    : > "$raw_out"

    if [ ! -e "$real_path" ]; then
        finalize_item "$item_id" "$section" "$rel_path" "$src_kind" "$display_cmd" "$logical_path" "" \
            "$req_root" "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$raw_out" "file not present: ${logical_path}"
        return 0
    fi
    if [ ! -r "$real_path" ]; then
        finalize_item "$item_id" "$section" "$rel_path" "$src_kind" "$display_cmd" "$logical_path" "" \
            "$req_root" "$item_start_iso" "$item_start_ms" 1 "permission_denied" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$raw_out" "cannot read ${logical_path} (uid=${RUN_AS_UID})"
        return 0
    fi

    local rc=0
    if [ "$tail_lines" -gt 0 ]; then
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" tail -n "$tail_lines" "$real_path" || rc=$?
    else
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" cat "$real_path" || rc=$?
    fi
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local status
    status=$(classify_cmd_status "$rc" "$req_root" "$CMD_TIMEOUT_SEC" "$raw_out" 0 "$elapsed_ms")
    local note=""
    [ "$status" = "permission_denied" ] && note="cannot read ${logical_path} (uid=${RUN_AS_UID})"
    [ "$status" = "timeout" ] && note="timed out after ${CMD_TIMEOUT_SEC}s"

    finalize_item "$item_id" "$section" "$rel_path" "$src_kind" "$display_cmd" "$logical_path" "" \
        "$req_root" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "$do_redact" "false" "$raw_out" "$note"
}

# run_composite_list: runs one or more optional commands into one stable file;
# tracks whether any binary was installed, whether any timed out / hit permission denied / succeeded.
run_composite_list() {
    local item_id="$1" section="$2" rel_path="$3" req_root="$4" do_redact="$5"
    local display_cmd="$6" target="$7"
    shift 7
    [ "${1:-}" = "--" ] && shift

    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local combined="${SCRATCH_DIR}/comp_combined.tmp"
    local sub_raw="${SCRATCH_DIR}/comp_sub.tmp"
    : > "$combined"

    local found_any=0 ok_any=0 non_empty_any=0 perm_any=0 timeout_any=0 last_rc=127
    local sub bin rc st elapsed_ms limit_head
    for sub in "$@"; do
        limit_head=0
        case "$sub" in
            *\|head:*)
                limit_head="${sub##*|head:}"
                sub="${sub%|head:*}" ;;
        esac
        # shellcheck disable=SC2206
        local argv=($sub)
        bin="${argv[0]}"
        if ! command -v "$bin" >/dev/null 2>&1; then
            continue
        fi
        found_any=1
        : > "$sub_raw"
        local sub_start_ms
        sub_start_ms=$(now_ms)
        rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_raw" "${argv[@]}" || rc=$?
        elapsed_ms=$(( $(now_ms) - sub_start_ms ))
        [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
        st=$(classify_cmd_status "$rc" "$req_root" "$CMD_TIMEOUT_SEC" "$sub_raw" 0 "$elapsed_ms")
        last_rc="$rc"
        {
            printf '## %s\n' "$sub"
            if [ "$limit_head" -gt 0 ]; then
                head -n "$limit_head" "$sub_raw"
            else
                cat "$sub_raw"
            fi
            printf '\n'
        } >> "$combined"
        case "$st" in
            ok) ok_any=1; non_empty_any=1 ;;
            empty) ok_any=1 ;;
            timeout) timeout_any=1 ;;
            permission_denied) perm_any=1 ;;
        esac
    done

    local status note="" final_rc="$last_rc"
    if [ "$found_any" -eq 0 ]; then
        status="command_missing"
        final_rc=127
        note="no matching command available"
    elif [ "$timeout_any" -eq 1 ]; then
        status="timeout"
        final_rc=124
        note="subcommand timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$ok_any" -eq 1 ]; then
        if [ "$non_empty_any" -eq 1 ]; then
            status="ok"
        else
            status="empty"
        fi
        final_rc=0
    elif [ "$perm_any" -eq 1 ]; then
        status="permission_denied"
        note="requires root privileges (uid=${RUN_AS_UID})"
    else
        status="failed"
    fi

    finalize_item "$item_id" "$section" "$rel_path" "composite" "$display_cmd" "" "$target" \
        "$req_root" "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "$do_redact" "false" "$combined" "$note"
}

# Specialized collectors for credential restriction & special semantics

collect_crontab() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_cron="${SCRATCH_DIR}/cron_raw.tmp"
    local summary_out="${SCRATCH_DIR}/cron_summary.tmp"
    : > "$raw_cron"
    : > "$summary_out"

    local cron_rc=0 cron_state="unavailable" status="ok" note=""
    if ! command -v crontab >/dev/null 2>&1; then
        cron_rc=127
        cron_state="command_missing"
    else
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_cron" crontab -l || cron_rc=$?
        if [ "$cron_rc" -eq 124 ]; then
            cron_state="timeout"
        elif [ "$cron_rc" -eq 0 ]; then
            cron_state="present"
        elif grep -qi 'no crontab for' "$raw_cron" 2>/dev/null; then
            cron_state="empty"
            cron_rc=0
            : > "$raw_cron"
        elif [ "$IS_ROOT" != "true" ] && is_permission_error_text "$raw_cron"; then
            cron_state="permission_denied"
        else
            cron_state="failed"
        fi
    fi

    {
        printf 'crontab_status=%s\n' "$cron_state"
        if [ "$cron_state" = "present" ]; then
            # Emit schedule + executable basename ONLY; drop all env values, comments, and args.
            awk '
            BEGIN { active = 0; env_cnt = 0; comment_cnt = 0 }
            /^[[:space:]]*$/ { next }
            /^[[:space:]]*#/ { comment_cnt++; next }
            /^[[:space:]]*[A-Za-z_][A-Za-z0-9_]*[[:space:]]*=/ { env_cnt++; next }
            {
                active++
                n = split($0, f, /[[:space:]]+/)
                if (substr(f[1], 1, 1) == "@") {
                    sched = f[1]
                    idx = 2
                } else if (n >= 6) {
                    sched = f[1] " " f[2] " " f[3] " " f[4] " " f[5]
                    idx = 6
                } else {
                    printf "entry=%s [unparsed_line_omitted]\n", f[1]
                    next
                }
                while (idx <= n && f[idx] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) {
                    idx++
                }
                cmd_tok = (idx <= n) ? f[idx] : "unknown"
                sub(/^.*\//, "", cmd_tok)
                sub(/[=:@?].*$/, "", cmd_tok)
                if (cmd_tok == "") cmd_tok = "command"
                printf "entry=%s %s [args omitted]\n", sched, cmd_tok
            }
            END {
                printf "crontab_active_entries=%d\n", active
                printf "crontab_env_assignments_omitted=%d\n", env_cnt
                printf "crontab_comments_omitted=%d\n", comment_cnt
            }' "$raw_cron"
        elif [ "$cron_state" = "empty" ]; then
            printf 'crontab_active_entries=0\n'
            printf 'crontab_env_assignments_omitted=0\n'
            printf 'crontab_comments_omitted=0\n'
        fi

        local crond_dir="${ROOT_PREFIX}/etc/cron.d"
        printf '\n## ls -l /etc/cron.d/\n'
        if [ -d "$crond_dir" ]; then
            ls -l "$crond_dir" 2>&1 || true
        else
            printf '[directory not present: /etc/cron.d]\n'
        fi
    } > "$summary_out"

    case "$cron_state" in
        timeout) status="timeout"; note="crontab timed out after ${CMD_TIMEOUT_SEC}s" ;;
        permission_denied) status="permission_denied"; note="crontab requires privilege (uid=${RUN_AS_UID})" ;;
        command_missing)
            if [ -d "${ROOT_PREFIX}/etc/cron.d" ]; then
                status="ok"; cron_rc=0; note="crontab missing; /etc/cron.d listing collected"
            else
                status="command_missing"; note="crontab not installed"
            fi ;;
        failed) status="failed" ;;
        *) status="ok" ;;
    esac

    finalize_item "system.crontab" "system" "system/crontab.log" "composite" \
        "crontab -l (schedule & executable basename only; env/args omitted); ls -l /etc/cron.d/" \
        "crontab,/etc/cron.d" "" "false" "$item_start_iso" "$item_start_ms" \
        "$cron_rc" "$status" "$CMD_TIMEOUT_SEC" "true" "true" "$summary_out" "$note"
}

collect_ps_top() {
    local item_id="$1" rel_path="$2" sort_key="$3"
    local display_cmd="ps -eo pid,user:20,%cpu,%mem,vsz,rss,stat,start_time,time,comm --sort=-${sort_key} | head -n 11"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/ps_raw.tmp"
    local filtered_out="${SCRATCH_DIR}/ps_top.tmp"
    : > "$raw_out"
    : > "$filtered_out"

    if ! command -v ps >/dev/null 2>&1; then
        finalize_item "$item_id" "performance" "$rel_path" "command" "$display_cmd" "ps" "" \
            "false" "$item_start_iso" "$item_start_ms" 127 "command_missing" "$CMD_TIMEOUT_SEC" \
            "false" "true" "$filtered_out" "command not found: ps"
        return 0
    fi

    local rc=0
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" \
        ps -eo pid,user:20,%cpu,%mem,vsz,rss,stat,start_time,time,comm "--sort=-${sort_key}" || rc=$?
    if [ "$rc" -ne 0 ] && [ "$rc" -ne 124 ]; then
        # Portable fallback without --sort, still strictly omitting raw command arguments.
        rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" \
            ps -eo pid,user,pcpu,pmem,vsz,rss,stat,time,comm || rc=$?
    fi
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local status
    status=$(classify_cmd_status "$rc" "false" "$CMD_TIMEOUT_SEC" "$raw_out" 0 "$elapsed_ms")
    head -n 11 "$raw_out" > "$filtered_out"

    finalize_item "$item_id" "performance" "$rel_path" "command" "$display_cmd" "ps" "" \
        "false" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "true" "$filtered_out" ""
}

collect_ps_count() {
    local display_cmd="ps -eo stat= (total/zombie/uninterruptible process counts)"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/ps_stat.tmp"
    local out_file="${SCRATCH_DIR}/ps_count.tmp"
    : > "$raw_out"
    : > "$out_file"

    if ! command -v ps >/dev/null 2>&1; then
        finalize_item "performance.ps_count" "performance" "performance/ps-count.log" "command" \
            "$display_cmd" "ps" "" "false" "$item_start_iso" "$item_start_ms" 127 "command_missing" \
            "$CMD_TIMEOUT_SEC" "false" "true" "$out_file" "command not found: ps"
        return 0
    fi

    local rc=0
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" ps -eo stat= || rc=$?
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local status
    status=$(classify_cmd_status "$rc" "false" "$CMD_TIMEOUT_SEC" "$raw_out" 0 "$elapsed_ms")
    if [ "$status" = "ok" ] || [ "$status" = "empty" ]; then
        awk '
        BEGIN { total = 0; zombie = 0; unint = 0 }
        NF > 0 {
            total++
            if ($1 ~ /^Z/) zombie++
            if ($1 ~ /^D/) unint++
        }
        END {
            printf "total_processes=%d\n", total
            printf "zombie_processes=%d\n", zombie
            printf "uninterruptible_d_processes=%d\n", unint
        }' "$raw_out" > "$out_file"
        status="ok"
    else
        cp "$raw_out" "$out_file"
    fi

    finalize_item "performance.ps_count" "performance" "performance/ps-count.log" "command" \
        "$display_cmd" "ps" "" "false" "$item_start_iso" "$item_start_ms" "$rc" "$status" \
        "$CMD_TIMEOUT_SEC" "false" "true" "$out_file" ""
}

collect_swap() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/swap.tmp"
    local sub_tmp="${SCRATCH_DIR}/swap_sub.tmp"
    : > "$out_file"

    local any_src=0 ok_any=0 non_empty_any=0 timeout_any=0 last_rc=-1
    if command -v swapon >/dev/null 2>&1; then
        any_src=1
        local rc=0
        : > "$sub_tmp"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" swapon -s || rc=$?
        printf '## swapon -s\n' >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
        [ "$rc" -eq 124 ] && timeout_any=1
        if [ "$rc" -eq 0 ]; then
            ok_any=1
            grep -q '[^[:space:]]' "$sub_tmp" 2>/dev/null && non_empty_any=1
        fi
        last_rc="$rc"
    fi
    local swaps_file="${ROOT_PREFIX}/proc/swaps"
    if [ -r "$swaps_file" ]; then
        any_src=1
        local rc=0
        : > "$sub_tmp"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" cat "$swaps_file" || rc=$?
        printf '## cat /proc/swaps\n' >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
        [ "$rc" -eq 124 ] && timeout_any=1
        if [ "$rc" -eq 0 ]; then
            ok_any=1
            grep -q '[^[:space:]]' "$sub_tmp" 2>/dev/null && non_empty_any=1
        fi
        last_rc="$rc"
    fi

    local status note=""
    if [ "$any_src" -eq 0 ]; then
        status="not_applicable"; last_rc=-1; note="swapon and /proc/swaps not available"
    elif [ "$timeout_any" -eq 1 ]; then
        status="timeout"; last_rc=124; note="timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$ok_any" -eq 1 ]; then
        [ "$non_empty_any" -eq 1 ] && status="ok" || status="empty"
        last_rc=0
    else
        status="failed"
    fi

    finalize_item "performance.swap" "performance" "performance/swap.log" "composite" \
        "swapon -s; cat /proc/swaps" "swapon,/proc/swaps" "" "false" \
        "$item_start_iso" "$item_start_ms" "$last_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "false" "$out_file" "$note"
}

collect_bonding() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/bonding.tmp"
    : > "$out_file"
    local bond_dir="${ROOT_PREFIX}/proc/net/bonding"
    local found=0 f
    if [ -d "$bond_dir" ]; then
        for f in "$bond_dir"/*; do
            [ -f "$f" ] || continue
            found=1
            printf '## %s\n' "/proc/net/bonding/$(basename "$f")" >> "$out_file"
            cat "$f" >> "$out_file" 2>&1 || true
            printf '\n' >> "$out_file"
        done
    fi
    if [ "$found" -eq 0 ]; then
        finalize_item "network.bonding" "network" "network/bonding.log" "proc" \
            "cat /proc/net/bonding/*" "/proc/net/bonding" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" "no bonding interfaces present"
    else
        finalize_item "network.bonding" "network" "network/bonding.log" "proc" \
            "cat /proc/net/bonding/*" "/proc/net/bonding" "" "false" \
            "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" ""
    fi
}

collect_messages_tail() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/messages.tmp"
    local sub_tmp="${SCRATCH_DIR}/messages_sub.tmp"
    : > "$out_file"

    local found=0 readable=0 non_empty_any=0 perm_denied=0 timeout_hit=0 f real_f rc
    for f in /var/log/messages /var/log/syslog; do
        real_f="${ROOT_PREFIX}${f}"
        [ -e "$real_f" ] || continue
        found=1
        if [ ! -r "$real_f" ]; then
            perm_denied=1
            continue
        fi
        readable=1
        : > "$sub_tmp"
        rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" tail -n 500 "$real_f" || rc=$?
        if [ "$rc" -eq 124 ]; then
            timeout_hit=1
        fi
        grep -q '[^[:space:]]' "$sub_tmp" 2>/dev/null && non_empty_any=1
        printf '## tail -n 500 %s\n' "$f" >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
    done

    local status="ok" final_rc=0 note=""
    if [ "$timeout_hit" -eq 1 ]; then
        status="timeout"; final_rc=124; note="timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$found" -eq 0 ]; then
        status="not_applicable"; final_rc=-1; note="/var/log/messages and /var/log/syslog not present"
    elif [ "$readable" -eq 0 ] && [ "$perm_denied" -eq 1 ]; then
        status="permission_denied"; final_rc=1; note="system log files unreadable (uid=${RUN_AS_UID})"
    elif [ "$non_empty_any" -eq 0 ]; then
        status="empty"; final_rc=0
    fi

    finalize_item "logs.messages_tail" "logs" "logs/messages-tail.log" "file" \
        "tail -n 500 /var/log/messages; tail -n 500 /var/log/syslog" \
        "/var/log/messages,/var/log/syslog" "" "true" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$out_file" "$note"
}

collect_mcelog() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/mcelog.tmp"
    local sub_tmp="${SCRATCH_DIR}/mcelog_sub.tmp"
    : > "$out_file"

    local any_src=0 ok_any=0 non_empty_any=0 perm_any=0 timeout_any=0 last_rc=-1
    local mce_file="${ROOT_PREFIX}/var/log/mcelog"
    if [ -e "$mce_file" ]; then
        any_src=1
        if [ -r "$mce_file" ]; then
            local rc=0
            : > "$sub_tmp"
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" tail -n 200 "$mce_file" || rc=$?
            printf '## tail -n 200 /var/log/mcelog\n' >> "$out_file"
            cat "$sub_tmp" >> "$out_file"
            printf '\n' >> "$out_file"
            [ "$rc" -eq 124 ] && timeout_any=1
            if [ "$rc" -eq 0 ]; then
                ok_any=1
                grep -q '[^[:space:]]' "$sub_tmp" 2>/dev/null && non_empty_any=1
            fi
            last_rc="$rc"
        else
            perm_any=1
            last_rc=1
        fi
    fi
    if command -v edac-util >/dev/null 2>&1; then
        any_src=1
        local rc=0
        : > "$sub_tmp"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" edac-util -v || rc=$?
        printf '## edac-util -v\n' >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
        [ "$rc" -eq 124 ] && timeout_any=1
        if [ "$rc" -eq 0 ]; then
            ok_any=1
            grep -q '[^[:space:]]' "$sub_tmp" 2>/dev/null && non_empty_any=1
        fi
        last_rc="$rc"
    fi

    # Direct kernel sysfs EDAC counters (zero package dependency; covers RHEL 8/9 & systems without edac-util/mcelog)
    local edac_root="${ROOT_PREFIX}/sys/devices/system/edac/mc"
    if [ -d "$edac_root" ]; then
        local edac_tmp="${SCRATCH_DIR}/edac_sysfs.tmp"
        : > "$edac_tmp"
        local mc_found=0 mc_dir mc_id mc_name ce_c ue_c ce_ni ue_ni
        for mc_dir in "$edac_root"/mc[0-9]*; do
            [ -d "$mc_dir" ] || continue
            mc_found=1
            mc_id=$(basename "$mc_dir")
            mc_name=$(tr -d '\r\n' < "$mc_dir/mc_name" 2>/dev/null || true)
            ce_c=$(tr -d '[:space:]' < "$mc_dir/ce_count" 2>/dev/null || true)
            ue_c=$(tr -d '[:space:]' < "$mc_dir/ue_count" 2>/dev/null || true)
            ce_ni=$(tr -d '[:space:]' < "$mc_dir/ce_noinfo_count" 2>/dev/null || true)
            ue_ni=$(tr -d '[:space:]' < "$mc_dir/ue_noinfo_count" 2>/dev/null || true)
            printf 'mc=%s | name=%s | ce_count=%s | ue_count=%s' "$mc_id" "$mc_name" "$ce_c" "$ue_c" >> "$edac_tmp"
            [ -n "$ce_ni" ] && printf ' | ce_noinfo=%s' "$ce_ni" >> "$edac_tmp"
            [ -n "$ue_ni" ] && printf ' | ue_noinfo=%s' "$ue_ni" >> "$edac_tmp"
            printf '\n' >> "$edac_tmp"

            local dimm_any=0 d_dir d_id d_lbl d_ce d_ue d_sz
            for d_dir in "$mc_dir"/dimm[0-9]* "$mc_dir"/rank[0-9]*; do
                [ -d "$d_dir" ] || continue
                dimm_any=1
                d_id=$(basename "$d_dir")
                d_lbl=$(tr -d '\r\n' < "$d_dir/dimm_label" 2>/dev/null || true)
                d_ce=$(tr -d '[:space:]' < "$d_dir/dimm_ce_count" 2>/dev/null || true)
                d_ue=$(tr -d '[:space:]' < "$d_dir/dimm_ue_count" 2>/dev/null || true)
                d_sz=$(tr -d '[:space:]' < "$d_dir/size" 2>/dev/null || true)
                printf 'dimm=%s/%s | label=%s | size_mb=%s | ce_count=%s | ue_count=%s\n' \
                    "$mc_id" "$d_id" "$d_lbl" "$d_sz" "$d_ce" "$d_ue" >> "$edac_tmp"
            done
            if [ "$dimm_any" -eq 0 ]; then
                local cs_dir cs_id cs_ce cs_ue ch_f ch_lbl ch_lbls
                for cs_dir in "$mc_dir"/csrow[0-9]*; do
                    [ -d "$cs_dir" ] || continue
                    cs_id=$(basename "$cs_dir")
                    cs_ce=$(tr -d '[:space:]' < "$cs_dir/ce_count" 2>/dev/null || true)
                    cs_ue=$(tr -d '[:space:]' < "$cs_dir/ue_count" 2>/dev/null || true)
                    ch_lbls=""
                    for ch_f in "$cs_dir"/ch[0-9]*_dimm_label; do
                        [ -r "$ch_f" ] || continue
                        ch_lbl=$(tr -d '\r\n' < "$ch_f" 2>/dev/null || true)
                        [ -n "$ch_lbl" ] && ch_lbls="${ch_lbls:+${ch_lbls},}${ch_lbl}"
                    done
                    printf 'csrow=%s/%s | label=%s | ce_count=%s | ue_count=%s\n' \
                        "$mc_id" "$cs_id" "$ch_lbls" "$cs_ce" "$cs_ue" >> "$edac_tmp"
                done
            fi
        done
        if [ "$mc_found" -eq 1 ]; then
            any_src=1
            ok_any=1
            printf '## /sys/devices/system/edac/mc\n' >> "$out_file"
            cat "$edac_tmp" >> "$out_file"
            printf '\n' >> "$out_file"
            grep -q '[^[:space:]]' "$edac_tmp" 2>/dev/null && non_empty_any=1
            last_rc=0
        fi
    fi

    local status note=""
    if [ "$any_src" -eq 0 ]; then
        status="not_applicable"; last_rc=-1; note="/var/log/mcelog, edac-util and /sys/devices/system/edac/mc not available"
    elif [ "$timeout_any" -eq 1 ]; then
        status="timeout"; last_rc=124; note="timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$ok_any" -eq 1 ]; then
        [ "$non_empty_any" -eq 1 ] && status="ok" || status="empty"
        last_rc=0
    elif [ "$perm_any" -eq 1 ]; then
        status="permission_denied"; last_rc=1; note="cannot read /var/log/mcelog (uid=${RUN_AS_UID})"
    else
        status="failed"
    fi

    finalize_item "logs.mcelog" "logs" "logs/mcelog.log" "composite" \
        "tail -n 200 /var/log/mcelog; edac-util -v; /sys/devices/system/edac/mc" "/var/log/mcelog,edac-util,/sys/devices/system/edac/mc" "" "false" \
        "$item_start_iso" "$item_start_ms" "$last_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$out_file" "$note"
}

collect_journal() {
    local item_id="$1" rel_path="$2" boot_arg="$3" max_lines="$4"
    local display_cmd="journalctl -p err -b ${boot_arg} --no-pager -o short-iso -n ${max_lines}"
    [ -z "$boot_arg" ] && display_cmd="journalctl -p err -b --no-pager -o short-iso -n ${max_lines}"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/journal_raw.tmp"
    : > "$raw_out"

    if ! command -v journalctl >/dev/null 2>&1; then
        finalize_item "$item_id" "logs" "$rel_path" "command" "$display_cmd" "journalctl" "" \
            "false" "$item_start_iso" "$item_start_ms" 127 "command_missing" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$raw_out" "command not found: journalctl"
        return 0
    fi

    local rc=0
    if [ -n "$boot_arg" ]; then
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" journalctl -p err -b "$boot_arg" --no-pager -o short-iso -n "$max_lines" || rc=$?
    else
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" journalctl -p err -b --no-pager -o short-iso -n "$max_lines" || rc=$?
    fi
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0

    local status note=""
    if [ -n "$boot_arg" ] && [ "$rc" -ne 0 ] && grep -qiE 'Failed to look up boot|Specifying boot ID or boot offset has no effect|No journal files were found|No journal boot entry found' "$raw_out" 2>/dev/null; then
        status="not_applicable"
        note="no previous boot journal available"
    else
        status=$(classify_cmd_status "$rc" "false" "$CMD_TIMEOUT_SEC" "$raw_out" 0 "$elapsed_ms")
        [ "$status" = "permission_denied" ] && note="insufficient journal permissions (uid=${RUN_AS_UID})"
        [ "$status" = "timeout" ] && note="timed out after ${CMD_TIMEOUT_SEC}s"
    fi

    finalize_item "$item_id" "logs" "$rel_path" "command" "$display_cmd" "journalctl" "" \
        "false" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$raw_out" "$note"
}

collect_oom() {
    local display_cmd="dmesg -T | grep -iE 'out of memory|oom-killer|killed process' | tail -n 50"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/oom_raw.tmp"
    local filtered_out="${SCRATCH_DIR}/oom_filtered.tmp"
    : > "$raw_out"
    : > "$filtered_out"

    if ! command -v dmesg >/dev/null 2>&1; then
        finalize_item "logs.oom" "logs" "logs/oom.log" "command" "$display_cmd" "dmesg" "" \
            "false" "$item_start_iso" "$item_start_ms" 127 "command_missing" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$filtered_out" "command not found: dmesg"
        return 0
    fi

    local rc=0
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" dmesg -T || rc=$?
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local status note=""
    if [ "$rc" -eq 0 ]; then
        grep -iE 'out of memory|oom-killer|killed process' "$raw_out" 2>/dev/null | tail -n 50 > "$filtered_out" || true
        if [ -s "$filtered_out" ]; then
            status="ok"
        else
            status="empty"
        fi
    else
        cp "$raw_out" "$filtered_out"
        status=$(classify_cmd_status "$rc" "false" "$CMD_TIMEOUT_SEC" "$raw_out" 0 "$elapsed_ms")
        [ "$status" = "permission_denied" ] && note="dmesg restricted (uid=${RUN_AS_UID})"
        [ "$status" = "timeout" ] && note="timed out after ${CMD_TIMEOUT_SEC}s"
    fi

    finalize_item "logs.oom" "logs" "logs/oom.log" "command" "$display_cmd" "dmesg" "" \
        "false" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$filtered_out" "$note"
}

collect_lspci() {
    local display_cmd="lspci -vv"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local std_out="${SCRATCH_DIR}/lspci_out.tmp"
    local std_err="${SCRATCH_DIR}/lspci_err.tmp"
    local final_out="${SCRATCH_DIR}/lspci_final.tmp"
    : > "$std_out"
    : > "$std_err"
    : > "$final_out"

    if ! command -v lspci >/dev/null 2>&1; then
        finalize_item "hardware.lspci" "hardware" "hardware/lspci.log" "command" "$display_cmd" "lspci" "" \
            "false" "$item_start_iso" "$item_start_ms" 127 "command_missing" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$final_out" "command not found: lspci"
        return 0
    fi

    local rc=0
    exec_with_timeout_split "$CMD_TIMEOUT_SEC" "$std_out" "$std_err" lspci -vv || rc=$?
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0

    # When lspci succeeds with stdout, drop benign stderr warnings (e.g. pcilib: sysfs_read_vpd)
    # so they cannot break device stanzas; preserve stderr on error/empty output for diagnostics.
    if [ "$rc" -eq 0 ] && [ -s "$std_out" ]; then
        cp "$std_out" "$final_out"
    else
        cat "$std_out" "$std_err" > "$final_out" 2>/dev/null || true
    fi
    local status note=""
    status=$(classify_cmd_status "$rc" "false" "$CMD_TIMEOUT_SEC" "$final_out" 0 "$elapsed_ms")
    [ "$status" = "permission_denied" ] && note="requires root privileges (uid=${RUN_AS_UID})"
    [ "$status" = "timeout" ] && note="timed out after ${CMD_TIMEOUT_SEC}s"

    finalize_item "hardware.lspci" "hardware" "hardware/lspci.log" "command" "$display_cmd" "lspci" "" \
        "false" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "false" "$final_out" "$note"
}

collect_dmesg_hw() {
    local display_cmd="dmesg -T | grep -iE '<hardware/link/ecc/aer/raid/sata keywords>' | tail -n 200"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/dmesg_hw_raw.tmp"
    local filtered_out="${SCRATCH_DIR}/dmesg_hw_filtered.tmp"
    : > "$raw_out"
    : > "$filtered_out"

    if ! command -v dmesg >/dev/null 2>&1; then
        finalize_item "logs.dmesg_hw" "logs" "logs/dmesg-hw.log" "command" "$display_cmd" "dmesg" "" \
            "false" "$item_start_iso" "$item_start_ms" 127 "command_missing" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$filtered_out" "command not found: dmesg"
        return 0
    fi

    local rc=0
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" dmesg -T || rc=$?
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local status note=""
    if [ "$rc" -eq 0 ]; then
        grep -iE 'hardware error|machine check|(^|[^a-z0-9_])mce([^a-z0-9_]|$)|edac|pcieport.*error|pcie bus error|(^|[^a-z0-9_])aer([^a-z0-9_]|$)|megaraid.*(error|fault|reset|timeout|offline|fail)|mpt[23]sas.*(error|fault|reset|timeout|fail)|medium error|i/o error|failed command:|ata bus error|emask 0x|sense key|unhandled sense|temperature above threshold|cpu clock throttled' "$raw_out" 2>/dev/null \
            | grep -viE 'giving out device|edac mc: ver:|supports [0-9]+ mce banks|support is initialized|collector initialized' 2>/dev/null \
            | tail -n 200 > "$filtered_out" || true
        if [ -s "$filtered_out" ]; then
            status="ok"
        else
            status="empty"
        fi
    else
        cp "$raw_out" "$filtered_out"
        status=$(classify_cmd_status "$rc" "false" "$CMD_TIMEOUT_SEC" "$raw_out" 0 "$elapsed_ms")
        [ "$status" = "permission_denied" ] && note="dmesg restricted (uid=${RUN_AS_UID})"
        [ "$status" = "timeout" ] && note="timed out after ${CMD_TIMEOUT_SEC}s"
    fi

    finalize_item "logs.dmesg_hw" "logs" "logs/dmesg-hw.log" "command" "$display_cmd" "dmesg" "" \
        "false" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$filtered_out" "$note"
}

# ── Hardware RAID Controller & Management Tool Detection / Collection ──

RAID_CONTROLLER_DETECTED="false"
RAID_HAS_DELL_PERC=0
RAID_HAS_MEGARAID=0
RAID_HAS_ARCCONF=0
RAID_BIN_STORCLI=""
RAID_BIN_PERCCLI=""
RAID_BIN_MEGACLI=""
RAID_BIN_ARCCONF=""
RAID_BIN_SSACLI=""
RAID_BIN_SAS3IRCU=""
RAID_BIN_SAS2IRCU=""
RAID_BIN_SMARTCTL=""

# find_raid_bin <path_names_csv> <extra_abs_paths_csv>
# Resolves binary via PATH first, then standard vendor paths (honoring ROOT_PREFIX & ITCHECK_KEEP_PATH=1 isolation).
find_raid_bin() {
    local names_csv="$1"
    local extras_csv="$2"
    local old_ifs="$IFS" cand resolved
    IFS=','
    for cand in $names_csv; do
        [ -n "$cand" ] || continue
        resolved=$(command -v "$cand" 2>/dev/null || true)
        if [ -n "$resolved" ] && [ -x "$resolved" ] && [ ! -d "$resolved" ]; then
            IFS="$old_ifs"
            case "$resolved" in
                /*) printf '%s' "$resolved" ;;
                *)  printf '%s/%s' "$(pwd)" "${resolved#./}" ;;
            esac
            return 0
        fi
    done
    if [ -n "$ROOT_PREFIX" ] || [ "${ITCHECK_KEEP_PATH:-0}" != "1" ]; then
        for cand in $extras_csv; do
            [ -n "$cand" ] || continue
            resolved="${ROOT_PREFIX}${cand}"
            if [ -x "$resolved" ] && [ ! -d "$resolved" ]; then
                IFS="$old_ifs"
                printf '%s' "$resolved"
                return 0
            fi
        done
    fi
    IFS="$old_ifs"
    return 1
}

# logical_bin_path <resolved_bin>
# Strips ROOT_PREFIX (and ephemeral temp PATH prefixes under ITCHECK_KEEP_PATH=1) for deterministic reporting.
logical_bin_path() {
    local p="$1"
    [ -n "$p" ] || return 0
    if [ -n "$ROOT_PREFIX" ]; then
        case "$p" in
            "${ROOT_PREFIX}"/*)
                p="${p#"$ROOT_PREFIX"}" ;;
        esac
    fi
    if [ "${ITCHECK_KEEP_PATH:-0}" = "1" ]; then
        case "$p" in
            /opt/*|/usr/*|/sbin/*|/bin/*) ;;
            *) p=$(basename "$p") ;;
        esac
    fi
    printf '%s' "$p"
}

# probe_tool_version <tool_name> <bin_path>
# Fast read-only version probe (5s timeout, inside SCRATCH_DIR); returns empty string on failure.
probe_tool_version() {
    local tname="$1"
    local tbin="$2"
    [ -n "$tbin" ] || return 0
    local vtmp="${SCRATCH_DIR}/raid_ver.tmp"
    local vrc=0
    : > "$vtmp"
    case "$tname" in
        storcli|perccli)
            ( cd "$SCRATCH_DIR" && exec_with_timeout 5 "$vtmp" "$tbin" -v ) || vrc=$? ;;
        megacli)
            ( cd "$SCRATCH_DIR" && exec_with_timeout 5 "$vtmp" "$tbin" -v -NoLog ) || vrc=$? ;;
        arcconf)
            ( cd "$SCRATCH_DIR" && exec_with_timeout 5 "$vtmp" "$tbin" VERSION ) || vrc=$? ;;
        ssacli)
            ( cd "$SCRATCH_DIR" && exec_with_timeout 5 "$vtmp" "$tbin" version ) || vrc=$? ;;
        smartctl)
            ( cd "$SCRATCH_DIR" && exec_with_timeout 5 "$vtmp" "$tbin" --version ) || vrc=$? ;;
        *)
            return 0 ;;
    esac
    if [ "$vrc" -eq 0 ] && [ -s "$vtmp" ] && ! is_permission_error_text "$vtmp"; then
        awk '
        /^[[:space:]]*$/ { next }
        tolower($0) ~ /(ver|version|storcli|perccli|megacli|arcconf|ssacli|smartctl)/ {
            gsub(/^[[:space:]]+|[[:space:]]+$/, "")
            gsub(/[|]/, " ")
            print substr($0, 1, 100)
            exit
        }' "$vtmp" 2>/dev/null || true
    fi
}

# run_raid_cmd <id> <rel_path> <bin_origin> <display_cmd> <file_out_path_or_empty> <na_mode> -- <argv...>
# Runs a read-only RAID CLI command inside SCRATCH_DIR so side-effect logs (MegaSAS.log/UCLI.log) never pollute CWD.
run_raid_cmd() {
    local item_id="$1" rel_path="$2" bin_origin="$3" display_cmd="$4" file_out="$5" na_mode="$6"
    shift 6
    [ "${1:-}" = "--" ] && shift

    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/raid_cmd_raw.tmp"
    local final_body="${SCRATCH_DIR}/raid_cmd_body.tmp"
    : > "$raw_out"
    : > "$final_body"
    [ -n "$file_out" ] && rm -f "$file_out" 2>/dev/null || true

    local rc=0
    ( cd "$SCRATCH_DIR" && exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" "$@" ) || rc=$?
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0

    # For commands exporting to a temp file (show events file=... / -AdpEventLog -f ...), prefer the file when non-empty.
    if [ -n "$file_out" ] && [ -s "$file_out" ]; then
        cp "$file_out" "$final_body" 2>/dev/null || true
        rm -f "$file_out" 2>/dev/null || true
    else
        [ -n "$file_out" ] && rm -f "$file_out" 2>/dev/null || true
        cp "$raw_out" "$final_body" 2>/dev/null || true
    fi

    local status note=""
    if [ "$na_mode" = "bbu_cv" ] && grep -qiE 'use /c[x0-9]+/(cv|bbu)|battery is absent|cachevault is absent|bbu is not present|no bbu|not supported|number of controllers[[:space:]]*=[[:space:]]*0|controller not found|no controller|adapter[[:space:]]*0.*not found' "$final_body" 2>/dev/null; then
        status="not_applicable"
        note="not present or not applicable on this controller"
    elif [ "$na_mode" = "ctrl_zero" ] && grep -qiE 'number of controllers[[:space:]]*=[[:space:]]*0|no controller|controller not found|no lsi sas|no adapters found|error:[[:space:]]*no controllers' "$final_body" 2>/dev/null; then
        status="not_applicable"
        note="no matching RAID controller detected by tool"
    else
        status=$(classify_cmd_status "$rc" "true" "$CMD_TIMEOUT_SEC" "$final_body" 0 "$elapsed_ms")
        case "$status" in
            permission_denied) note="requires root privileges (uid=${RUN_AS_UID})" ;;
            timeout) note="timed out after ${CMD_TIMEOUT_SEC}s" ;;
        esac
    fi

    finalize_item "$item_id" "storage" "$rel_path" "command" "$display_cmd" "$bin_origin" "" \
        "true" "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$final_body" "$note"
}

collect_raid_detect() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)

    local pci_raw="${SCRATCH_DIR}/raid_lspci.tmp"
    local ctrl_list="${SCRATCH_DIR}/raid_ctrls.tmp"
    local drv_list="${SCRATCH_DIR}/raid_drvs.tmp"
    local out_file="${SCRATCH_DIR}/raid_detect.tmp"
    : > "$pci_raw"
    : > "$ctrl_list"
    : > "$drv_list"
    : > "$out_file"

    # 1. Detect hardware RAID controllers via lspci -nnk (primary)
    if command -v lspci >/dev/null 2>&1; then
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$pci_raw" lspci -nnk || true
        if [ -s "$pci_raw" ]; then
            awk '
            function classify_family(cls, vid, svid, drv, low_all) {
                if ((drv ~ /^megaraid/ || vid == "1000" || low_all ~ /(megaraid|lsi|broadcom|avago)/) && (svid == "1028" || low_all ~ /(^|[^a-z0-9])perc([^a-z0-9]|$)|poweredge.*raid/)) {
                    return "dell_perc"
                }
                if (drv ~ /^megaraid/ || (vid == "1000" && (cls == "0104" || low_all ~ /(megaraid|raid|3108|3508|3516|3908|3916|2208|2108|3808|3816|serveraid m)/))) {
                    return "megaraid"
                }
                if (drv == "hpsa" || drv == "cciss" || low_all ~ /smart array/ || (drv == "smartpqi" && (svid == "103c" || svid == "1590" || low_all ~ /(hewlett|hpe|p408|p816|e208|sr416|sr100)/))) {
                    return "hpe_ssa"
                }
                if (drv == "aacraid" || drv == "smartpqi" || vid == "9005" || vid == "11f8" || low_all ~ /(adaptec|microsemi|microchip|smartraid|pmc-sierra|serveraid)/) {
                    return "arcconf"
                }
                if (drv == "spraid" || (vid == "19e5" && (cls == "0104" || low_all ~ /(raid|hi1880|spraid)/))) {
                    return "huawei_spraid"
                }
                if (drv == "mpt3sas" || drv == "mpt2sas" || drv == "mptsas" || drv == "mpi3mr" || (vid == "1000" && (cls == "0107" || low_all ~ /(sas2008|sas2308|sas3008|sas3408|sas3416|sas3808|fusion-mpt|serial attached scsi)/))) {
                    return "lsi_ir"
                }
                if (vid == "8086" && (cls == "0104" || low_all ~ /(vmd|volume management device|rste|vroc|raid)/)) {
                    return "intel_vroc_rste"
                }
                if (drv ~ /^3w/ || low_all ~ /3ware/) {
                    return "tw_cli"
                }
                if (drv == "arcmsr" || low_all ~ /areca/) {
                    return "areca"
                }
                return "generic_raid"
            }
            function is_raid_driver(d) {
                return (d ~ /^(megaraid_sas|megaraid_mbox|megaraid_mm|mpi3mr|hpsa|cciss|smartpqi|aacraid|mpt3sas|mpt2sas|mptsas|3w[-_]9xxx|3w[-_]sas|3w[-_]xxxx|arcmsr|spraid|pmcraid|ipr)$/)
            }
            function extract_last_idpair(s,   tmp, pair) {
                tmp = s
                pair = ""
                while (match(tmp, /\[[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]\]/)) {
                    pair = tolower(substr(tmp, RSTART + 1, RLENGTH - 2))
                    tmp = substr(tmp, RSTART + RLENGTH)
                }
                return pair
            }
            function flush_dev(   low_cls, low_all, is_virt, is_hit, fam, clean_desc) {
                if (bdf == "") return
                low_cls = tolower(cls_text)
                low_all = tolower(cls_text " " desc " " subsys)
                is_virt = (low_all ~ /(virtio|vmware|qemu|xen|hyper-v|red hat, inc\.)/)
                is_hit = 0
                if (is_raid_driver(drv) || is_raid_driver(mod)) {
                    is_hit = 1
                } else if (!is_virt && (pci_cls == "0104" || low_cls ~ /raid/)) {
                    is_hit = 1
                } else if (!is_virt && pci_cls == "0107" && (vid == "1000" || vid == "9005" || vid == "103c" || vid == "19e5")) {
                    is_hit = 1
                }
                if (is_hit) {
                    eff_drv = (drv != "") ? drv : mod
                    fam = classify_family(pci_cls, vid, svid, eff_drv, low_all)
                    clean_desc = desc
                    if (subsys != "") clean_desc = clean_desc " (" subsys ")"
                    gsub(/[|]/, " ", clean_desc)
                    printf "controller=%d | bdf=%s | pci_class=%s | vendor_id=%s | device_id=%s | subsys_vendor=%s | driver=%s | family=%s | description=%s\n", \
                        idx++, bdf, pci_cls, vid, did, svid, eff_drv, fam, clean_desc
                }
                bdf = ""; cls_text = ""; pci_cls = ""; desc = ""; vid = ""; did = ""; subsys = ""; svid = ""; drv = ""; mod = ""
            }
            BEGIN { idx = 0; bdf = "" }
            /^([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]:)?[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]\.[0-9a-fA-F][[:space:]]+/ {
                flush_dev()
                line = $0
                sp = index(line, " ")
                bdf = substr(line, 1, sp - 1)
                rest = substr(line, sp + 1)
                sub(/^[[:space:]]+/, "", rest)
                cpos = index(rest, ":")
                if (cpos > 0) {
                    cls_text = substr(rest, 1, cpos - 1)
                    desc = substr(rest, cpos + 1)
                    sub(/^[[:space:]]+/, "", desc)
                } else {
                    cls_text = rest
                    desc = ""
                }
                if (match(cls_text, /\[[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]\]/)) {
                    pci_cls = tolower(substr(cls_text, RSTART + 1, 4))
                }
                pair = extract_last_idpair(desc)
                if (pair != "") {
                    vid = substr(pair, 1, 4)
                    did = substr(pair, 6, 4)
                }
                next
            }
            /^[[:space:]]+Subsystem:/ {
                s = $0
                sub(/^[[:space:]]+Subsystem:[[:space:]]*/, "", s)
                subsys = s
                pair = extract_last_idpair(s)
                if (pair != "") {
                    svid = substr(pair, 1, 4)
                }
                next
            }
            /^[[:space:]]+Kernel driver in use:/ {
                s = $0
                sub(/^[[:space:]]+Kernel driver in use:[[:space:]]*/, "", s)
                sub(/[[:space:]]+$/, "", s)
                drv = s
                next
            }
            /^[[:space:]]+Kernel modules:/ {
                s = $0
                sub(/^[[:space:]]+Kernel modules:[[:space:]]*/, "", s)
                sub(/[,[:space:]].*$/, "", s)
                mod = s
                next
            }
            END { flush_dev() }
            ' "$pci_raw" > "$ctrl_list" 2>/dev/null || true
        fi
    fi

    # 2. Fallback: scan sysfs PCI devices if lspci was unavailable or found nothing
    local sys_pci="${ROOT_PREFIX}/sys/bus/pci/devices"
    if [ ! -s "$ctrl_list" ] && [ -d "$sys_pci" ]; then
        local pdev pbdf pcls pvid pdid psvid pdrv pfam pidx=0
        for pdev in "$sys_pci"/*; do
            [ -d "$pdev" ] || continue
            pbdf=$(basename "$pdev")
            pcls=$(awk '{ s = tolower($1); sub(/^0x/, "", s); print substr(s, 1, 4); exit }' "$pdev/class" 2>/dev/null || true)
            pvid=$(awk '{ s = tolower($1); sub(/^0x/, "", s); print s; exit }' "$pdev/vendor" 2>/dev/null || true)
            pdid=$(awk '{ s = tolower($1); sub(/^0x/, "", s); print s; exit }' "$pdev/device" 2>/dev/null || true)
            psvid=$(awk '{ s = tolower($1); sub(/^0x/, "", s); print s; exit }' "$pdev/subsystem_vendor" 2>/dev/null || true)
            pdrv=$(awk -F= '$1=="DRIVER"{print $2; exit}' "$pdev/uevent" 2>/dev/null || true)
            local is_raid=0
            case "$pdrv" in
                megaraid_sas|megaraid_mbox|megaraid_mm|mpi3mr|hpsa|cciss|smartpqi|aacraid|mpt3sas|mpt2sas|mptsas|3w_9xxx|3w-9xxx|3w_sas|3w-sas|3w_xxxx|3w-xxxx|arcmsr|spraid|pmcraid|ipr)
                    is_raid=1 ;;
            esac
            if [ "$is_raid" -eq 0 ] && [ "$pcls" = "0104" ]; then
                case "$pvid" in
                    1af4|15ad|1b36|5853|1414) ;; # skip virtual vendors
                    *) is_raid=1 ;;
                esac
            fi
            if [ "$is_raid" -eq 0 ] && [ "$pcls" = "0107" ]; then
                case "$pvid" in
                    1000|9005|103c|19e5) is_raid=1 ;;
                esac
            fi
            if [ "$is_raid" -eq 1 ]; then
                pfam="generic_raid"
                if [ "$pdrv" = "megaraid_sas" ] || [ "$pdrv" = "megaraid_mbox" ] || [ "$pdrv" = "megaraid_mm" ] || [ "$pvid" = "1000" ]; then
                    if [ "$psvid" = "1028" ]; then
                        pfam="dell_perc"
                    elif [ "$pdrv" = "mpt3sas" ] || [ "$pdrv" = "mpt2sas" ] || [ "$pdrv" = "mptsas" ] || [ "$pdrv" = "mpi3mr" ]; then
                        pfam="lsi_ir"
                    else
                        pfam="megaraid"
                    fi
                elif [ "$pdrv" = "hpsa" ] || [ "$pdrv" = "cciss" ] || { [ "$pdrv" = "smartpqi" ] && { [ "$psvid" = "103c" ] || [ "$psvid" = "1590" ]; }; }; then
                    pfam="hpe_ssa"
                elif [ "$pdrv" = "aacraid" ] || [ "$pdrv" = "smartpqi" ] || [ "$pvid" = "9005" ] || [ "$pvid" = "11f8" ]; then
                    pfam="arcconf"
                elif [ "$pdrv" = "spraid" ] || [ "$pvid" = "19e5" ]; then
                    pfam="huawei_spraid"
                elif [ "$pvid" = "8086" ]; then
                    pfam="intel_vroc_rste"
                elif [ "$pdrv" = "arcmsr" ]; then
                    pfam="areca"
                fi
                printf 'controller=%d | bdf=%s | pci_class=%s | vendor_id=%s | device_id=%s | subsys_vendor=%s | driver=%s | family=%s | description=PCI %s:%s (class %s)\n' \
                    "$pidx" "$pbdf" "$pcls" "$pvid" "$pdid" "$psvid" "$pdrv" "$pfam" "$pvid" "$pdid" "$pcls" >> "$ctrl_list"
                pidx=$((pidx + 1))
            fi
        done
    fi

    # 3. Loaded hardware RAID drivers from /proc/modules and /sys/class/scsi_host/*/proc_name
    local proc_mod="${ROOT_PREFIX}/proc/modules"
    if [ -r "$proc_mod" ]; then
        awk '$1 ~ /^(megaraid_sas|megaraid_mbox|megaraid_mm|mpi3mr|hpsa|cciss|smartpqi|aacraid|mpt3sas|mpt2sas|mptsas|3w_9xxx|3w_sas|3w_xxxx|arcmsr|spraid|pmcraid|ipr)$/ { print $1 }' "$proc_mod" 2>/dev/null >> "$drv_list" || true
    fi
    local scsi_host_dir="${ROOT_PREFIX}/sys/class/scsi_host"
    if [ -d "$scsi_host_dir" ]; then
        local shost pname
        for shost in "$scsi_host_dir"/host*; do
            [ -r "$shost/proc_name" ] || continue
            pname=$(tr -d '[:space:]' < "$shost/proc_name" 2>/dev/null || true)
            case "$pname" in
                megaraid_sas|megaraid_mbox|megaraid_mm|mpi3mr|hpsa|cciss|smartpqi|aacraid|mpt3sas|mpt2sas|mptsas|3w-9xxx|3w_9xxx|3w-sas|3w_sas|3w-xxxx|3w_xxxx|arcmsr|spraid|pmcraid|ipr)
                    printf '%s\n' "$pname" >> "$drv_list" ;;
            esac
        done
    fi
    if [ -s "$drv_list" ]; then
        LC_ALL=C sort -u "$drv_list" > "${drv_list}.uniq" && mv "${drv_list}.uniq" "$drv_list"
    fi

    # If no PCI controller lines were obtained but a hardware RAID kernel driver IS loaded, record driver-based detection.
    if [ ! -s "$ctrl_list" ] && [ -s "$drv_list" ]; then
        local didx=0 dname dfam
        while IFS= read -r dname; do
            [ -n "$dname" ] || continue
            case "$dname" in
                megaraid_*) dfam="megaraid" ;;
                hpsa|cciss) dfam="hpe_ssa" ;;
                aacraid|smartpqi) dfam="arcconf" ;;
                mpt3sas|mpt2sas|mptsas|mpi3mr) dfam="lsi_ir" ;;
                spraid) dfam="huawei_spraid" ;;
                3w*) dfam="tw_cli" ;;
                arcmsr) dfam="areca" ;;
                *) dfam="generic_raid" ;;
            esac
            printf 'controller=%d | bdf=unknown | pci_class= | vendor_id= | device_id= | subsys_vendor= | driver=%s | family=%s | description=Detected via loaded kernel driver %s\n' \
                "$didx" "$dname" "$dfam" "$dname" >> "$ctrl_list"
            didx=$((didx + 1))
        done < "$drv_list"
    fi

    # 4. Probe RAID & disk health management tools
    RAID_BIN_STORCLI=$(find_raid_bin "storcli64,storcli,storcli2" \
        "/opt/MegaRAID/storcli/storcli64,/opt/MegaRAID/storcli/storcli,/opt/MegaRAID/storcli2/storcli2,/opt/lsi/storcli/storcli64,/opt/lsi/storcli/storcli,/usr/local/sbin/storcli64,/usr/local/sbin/storcli,/usr/sbin/storcli64,/usr/sbin/storcli,/sbin/storcli64,/sbin/storcli" || true)
    RAID_BIN_PERCCLI=$(find_raid_bin "perccli64,perccli,perccli2" \
        "/opt/MegaRAID/perccli/perccli64,/opt/MegaRAID/perccli/perccli,/opt/MegaRAID/perccli2/perccli2,/opt/dell/srvadmin/sbin/perccli64,/opt/dell/srvadmin/bin/perccli64,/usr/local/sbin/perccli64,/usr/local/sbin/perccli,/usr/sbin/perccli64,/usr/sbin/perccli,/sbin/perccli64,/sbin/perccli" || true)
    RAID_BIN_MEGACLI=$(find_raid_bin "MegaCli64,MegaCli,megacli64,megacli" \
        "/opt/MegaRAID/MegaCli/MegaCli64,/opt/MegaRAID/MegaCli/MegaCli,/opt/lsi/MegaCLI/MegaCli64,/opt/lsi/MegaCLI/MegaCli,/usr/local/sbin/MegaCli64,/usr/sbin/MegaCli64,/sbin/MegaCli64,/usr/sbin/megacli" || true)
    RAID_BIN_ARCCONF=$(find_raid_bin "arcconf,ARCCONF" \
        "/usr/StorMan/arcconf,/usr/Arcconf/arcconf,/opt/arcconf/arcconf,/opt/Microsemi/arcconf/arcconf,/opt/Microchip/arcconf/arcconf,/usr/local/sbin/arcconf,/usr/sbin/arcconf,/sbin/arcconf" || true)
    RAID_BIN_SSACLI=$(find_raid_bin "ssacli,hpssacli,hpacucli" \
        "/usr/sbin/ssacli,/usr/sbin/hpssacli,/usr/sbin/hpacucli,/opt/smartstorageadmin/ssacli/bin/ssacli,/opt/hp/hpssacli/bin/hpssacli" || true)
    RAID_BIN_SAS3IRCU=$(find_raid_bin "sas3ircu" \
        "/usr/local/sbin/sas3ircu,/usr/sbin/sas3ircu,/sbin/sas3ircu,/opt/lsi/sas3ircu/sas3ircu" || true)
    RAID_BIN_SAS2IRCU=$(find_raid_bin "sas2ircu" \
        "/usr/local/sbin/sas2ircu,/usr/sbin/sas2ircu,/sbin/sas2ircu,/opt/lsi/sas2ircu/sas2ircu" || true)
    RAID_BIN_SMARTCTL=$(find_raid_bin "smartctl" \
        "/usr/sbin/smartctl,/sbin/smartctl,/usr/local/sbin/smartctl" || true)

    local ctrl_cnt=0
    if [ -s "$ctrl_list" ]; then
        ctrl_cnt=$(wc -l < "$ctrl_list" | tr -d '[:space:]')
        [ "${ctrl_cnt:-0}" -gt 0 ] && RAID_CONTROLLER_DETECTED="true"
    fi
    grep -q 'family=dell_perc' "$ctrl_list" 2>/dev/null && RAID_HAS_DELL_PERC=1
    grep -qE 'family=(megaraid|dell_perc)' "$ctrl_list" 2>/dev/null && RAID_HAS_MEGARAID=1
    grep -q 'family=arcconf' "$ctrl_list" 2>/dev/null && RAID_HAS_ARCCONF=1

    local families="none" drivers_csv="none" installed_raid="none" raid_tool_avail="false" smartctl_avail="false"
    if [ -s "$ctrl_list" ]; then
        families=$(awk -F'|' '{ for (i=1; i<=NF; i++) { if ($i ~ /family=/) { s=$i; sub(/^.*family=/,"",s); gsub(/[[:space:]]/,"",s); if (s!="") print s } } }' "$ctrl_list" | LC_ALL=C sort -u | awk '{ out = (out == "" ? $0 : out "," $0) } END { print out }' 2>/dev/null || true)
        [ -z "$families" ] && families="none"
    fi
    if [ -s "$drv_list" ]; then
        drivers_csv=$(awk '{ out = (out == "" ? $0 : out "," $0) } END { print out }' "$drv_list" 2>/dev/null || true)
        [ -z "$drivers_csv" ] && drivers_csv="none"
    fi

    local tlist=""
    [ -n "$RAID_BIN_STORCLI" ]  && tlist="${tlist:+${tlist},}storcli"
    [ -n "$RAID_BIN_PERCCLI" ]  && tlist="${tlist:+${tlist},}perccli"
    [ -n "$RAID_BIN_MEGACLI" ]  && tlist="${tlist:+${tlist},}megacli"
    [ -n "$RAID_BIN_ARCCONF" ]  && tlist="${tlist:+${tlist},}arcconf"
    [ -n "$RAID_BIN_SSACLI" ]   && tlist="${tlist:+${tlist},}ssacli"
    [ -n "$RAID_BIN_SAS3IRCU" ] && tlist="${tlist:+${tlist},}sas3ircu"
    [ -n "$RAID_BIN_SAS2IRCU" ] && tlist="${tlist:+${tlist},}sas2ircu"
    if [ -n "$tlist" ]; then
        raid_tool_avail="true"
        installed_raid="$tlist"
    fi
    [ -n "$RAID_BIN_SMARTCTL" ] && smartctl_avail="true"

    {
        printf 'raid_controller_detected=%s\n' "$RAID_CONTROLLER_DETECTED"
        printf 'raid_controller_count=%s\n' "${ctrl_cnt:-0}"
        printf 'raid_tool_available=%s\n' "$raid_tool_avail"
        printf 'smartctl_available=%s\n' "$smartctl_avail"
        printf 'detected_families=%s\n' "$families"
        printf 'active_raid_drivers=%s\n' "$drivers_csv"
        printf 'installed_raid_tools=%s\n' "$installed_raid"
        printf '\n## detected_controllers\n'
        if [ -s "$ctrl_list" ]; then
            cat "$ctrl_list"
        else
            printf 'none\n'
        fi
        printf '\n## loaded_raid_drivers\n'
        if [ -s "$drv_list" ]; then
            cat "$drv_list"
        else
            printf 'none\n'
        fi
        printf '\n## tool_inventory\n'
        local tname tbin tinst tver
        for tname in storcli perccli megacli arcconf ssacli sas3ircu sas2ircu smartctl; do
            case "$tname" in
                storcli)  tbin="$RAID_BIN_STORCLI" ;;
                perccli)  tbin="$RAID_BIN_PERCCLI" ;;
                megacli)  tbin="$RAID_BIN_MEGACLI" ;;
                arcconf)  tbin="$RAID_BIN_ARCCONF" ;;
                ssacli)   tbin="$RAID_BIN_SSACLI" ;;
                sas3ircu) tbin="$RAID_BIN_SAS3IRCU" ;;
                sas2ircu) tbin="$RAID_BIN_SAS2IRCU" ;;
                smartctl) tbin="$RAID_BIN_SMARTCTL" ;;
            esac
            if [ -n "$tbin" ]; then
                tinst="true"
                tver=$(probe_tool_version "$tname" "$tbin")
                tdisp=$(logical_bin_path "$tbin")
            else
                tinst="false"
                tver=""
                tdisp=""
            fi
            printf 'tool=%s | installed=%s | path=%s | version=%s\n' "$tname" "$tinst" "$tdisp" "$tver"
        done
    } > "$out_file"

    finalize_item "storage.raid_detect" "storage" "storage/raid-detect.log" "composite" \
        "RAID controller & management tool detection (lspci/sysfs/modules + StorCLI/PercCLI/MegaCLI/ARCCONF/SSACLI/SASxIRCU/smartctl)" \
        "lspci,/sys/bus/pci,/proc/modules" "" "false" \
        "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
        "false" "false" "$out_file" ""
}

collect_storcli_family() {
    local tag="$1"
    local bin="$2"
    local dbin
    dbin=$(logical_bin_path "$bin")
    local evt_tmp="${SCRATCH_DIR}/raid_${tag}_events.tmp"

    run_raid_cmd "storage.raid_${tag}_show_all" "storage/raid-${tag}-show-all.log" "$dbin" \
        "${dbin} /call show all" "" "ctrl_zero" -- "$bin" /call show all
    run_raid_cmd "storage.raid_${tag}_bbu" "storage/raid-${tag}-bbu.log" "$dbin" \
        "${dbin} /call/bbu show all" "" "bbu_cv" -- "$bin" /call/bbu show all
    run_raid_cmd "storage.raid_${tag}_cv" "storage/raid-${tag}-cv.log" "$dbin" \
        "${dbin} /call/cv show all" "" "bbu_cv" -- "$bin" /call/cv show all
    run_raid_cmd "storage.raid_${tag}_dall" "storage/raid-${tag}-dall.log" "$dbin" \
        "${dbin} /call/dall show all" "" "ctrl_zero" -- "$bin" /call/dall show all
    run_raid_cmd "storage.raid_${tag}_eall" "storage/raid-${tag}-eall.log" "$dbin" \
        "${dbin} /call/eall show all" "" "ctrl_zero" -- "$bin" /call/eall show all
    run_raid_cmd "storage.raid_${tag}_sall" "storage/raid-${tag}-sall.log" "$dbin" \
        "${dbin} /call/eall/sall show all" "" "ctrl_zero" -- "$bin" /call/eall/sall show all
    run_raid_cmd "storage.raid_${tag}_vall" "storage/raid-${tag}-vall.log" "$dbin" \
        "${dbin} /call/vall show all" "" "ctrl_zero" -- "$bin" /call/vall show all
    run_raid_cmd "storage.raid_${tag}_pall" "storage/raid-${tag}-pall.log" "$dbin" \
        "${dbin} /call/pall show all" "" "ctrl_zero" -- "$bin" /call/pall show all
    run_raid_cmd "storage.raid_${tag}_events" "storage/raid-${tag}-events.log" "$dbin" \
        "${dbin} /call show events file=<tmp>" "$evt_tmp" "ctrl_zero" -- "$bin" /call show events "file=${evt_tmp}"
    run_raid_cmd "storage.raid_${tag}_termlog" "storage/raid-${tag}-termlog.log" "$dbin" \
        "${dbin} /call show termlog" "" "ctrl_zero" -- "$bin" /call show termlog
}

collect_megacli() {
    local bin="$1"
    local dbin
    dbin=$(logical_bin_path "$bin")
    local evt_tmp="${SCRATCH_DIR}/raid_megacli_events.tmp"

    run_raid_cmd "storage.raid_megacli_adpallinfo" "storage/raid-megacli-adpallinfo.log" "$dbin" \
        "${dbin} -AdpAllInfo -aALL -NoLog" "" "ctrl_zero" -- "$bin" -AdpAllInfo -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_encinfo" "storage/raid-megacli-encinfo.log" "$dbin" \
        "${dbin} -EncInfo -aALL -NoLog" "" "ctrl_zero" -- "$bin" -EncInfo -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_pdlist" "storage/raid-megacli-pdlist.log" "$dbin" \
        "${dbin} -PDList -aALL -NoLog" "" "ctrl_zero" -- "$bin" -PDList -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_ldinfo" "storage/raid-megacli-ldinfo.log" "$dbin" \
        "${dbin} -LDInfo -Lall -aALL -NoLog" "" "ctrl_zero" -- "$bin" -LDInfo -Lall -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_ldpdinfo" "storage/raid-megacli-ldpdinfo.log" "$dbin" \
        "${dbin} -LdPdInfo -aALL -NoLog" "" "ctrl_zero" -- "$bin" -LdPdInfo -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_bbu" "storage/raid-megacli-bbu.log" "$dbin" \
        "${dbin} -AdpBbuCmd -aALL -NoLog" "" "bbu_cv" -- "$bin" -AdpBbuCmd -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_phyerr" "storage/raid-megacli-phyerr.log" "$dbin" \
        "${dbin} -PhyErrorCounters -aALL -NoLog" "" "ctrl_zero" -- "$bin" -PhyErrorCounters -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_events" "storage/raid-megacli-events.log" "$dbin" \
        "${dbin} -AdpEventLog -GetEvents -f <tmp> -aALL -NoLog" "$evt_tmp" "ctrl_zero" -- \
        "$bin" -AdpEventLog -GetEvents -f "$evt_tmp" -aALL -NoLog
    run_raid_cmd "storage.raid_megacli_fwtermlog" "storage/raid-megacli-fwtermlog.log" "$dbin" \
        "${dbin} -FwTermLog Dsply -aALL -NoLog" "" "ctrl_zero" -- "$bin" -FwTermLog Dsply -aALL -NoLog
}

collect_arcconf_multi() {
    local item_id="$1" rel_path="$2" bin="$3" display_cmd="$4" sub_mode="$5" ctrl_ids="$6"
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local combined="${SCRATCH_DIR}/arc_combined.tmp"
    local sub_raw="${SCRATCH_DIR}/arc_sub.tmp"
    : > "$combined"

    local dbin
    dbin=$(logical_bin_path "$bin")
    local ok_any=0 non_empty_any=0 perm_any=0 timeout_any=0 last_rc=0 cid rc st elapsed_ms sub_start_ms
    for cid in $ctrl_ids; do
        local sub_cmds=""
        case "$sub_mode" in
            config) sub_cmds="GETCONFIG ${cid} AL" ;;
            status) sub_cmds="GETSTATUS ${cid}" ;;
            logs)   sub_cmds="GETLOGS ${cid} DEAD|GETLOGS ${cid} DEVICE|GETLOGS ${cid} EVENT" ;;
        esac
        local old_ifs="$IFS" scmd
        IFS='|'
        for scmd in $sub_cmds; do
            IFS="$old_ifs"
            # shellcheck disable=SC2206
            local argv=($scmd)
            : > "$sub_raw"
            sub_start_ms=$(now_ms)
            rc=0
            ( cd "$SCRATCH_DIR" && exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_raw" "$bin" "${argv[@]}" ) || rc=$?
            elapsed_ms=$(( $(now_ms) - sub_start_ms ))
            [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
            st=$(classify_cmd_status "$rc" "true" "$CMD_TIMEOUT_SEC" "$sub_raw" 0 "$elapsed_ms")
            last_rc="$rc"
            {
                printf '## %s %s\n' "$dbin" "$scmd"
                cat "$sub_raw"
                printf '\n'
            } >> "$combined"
            case "$st" in
                ok) ok_any=1; non_empty_any=1 ;;
                empty) ok_any=1 ;;
                timeout) timeout_any=1 ;;
                permission_denied) perm_any=1 ;;
            esac
            IFS='|'
        done
        IFS="$old_ifs"
    done

    local status note="" final_rc="$last_rc"
    if [ "$timeout_any" -eq 1 ]; then
        status="timeout"; final_rc=124; note="subcommand timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$ok_any" -eq 1 ]; then
        [ "$non_empty_any" -eq 1 ] && status="ok" || status="empty"
        final_rc=0
    elif [ "$perm_any" -eq 1 ]; then
        status="permission_denied"; note="requires root privileges (uid=${RUN_AS_UID})"
    else
        status="failed"
    fi

    finalize_item "$item_id" "storage" "$rel_path" "composite" "$display_cmd" "$dbin" "" \
        "true" "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$combined" "$note"
}

collect_arcconf() {
    local bin="$1"
    local dbin
    dbin=$(logical_bin_path "$bin")
    run_raid_cmd "storage.raid_arcconf_list" "storage/raid-arcconf-list.log" "$dbin" \
        "${dbin} LIST" "" "ctrl_zero" -- "$bin" LIST
    local list_file="${CFGDIR}/storage/raid-arcconf-list.log"
    local ctrl_ids=""
    if [ -r "$list_file" ]; then
        ctrl_ids=$(awk '
            /Controller[[:space:]]+[0-9]+/ {
                if (match($0, /Controller[[:space:]]+[0-9]+/)) {
                    s = substr($0, RSTART, RLENGTH)
                    sub(/^Controller[[:space:]]+/, "", s)
                    if (!seen[s]++) print s
                }
            }
            /^[[:space:]]*Controller[[:space:]]+ID/ { in_tbl = 1; next }
            in_tbl && /^[[:space:]]*[0-9]+[[:space:]]*:/ {
                s = $1; sub(/:.*/, "", s)
                if (s ~ /^[0-9]+$/ && !seen[s]++) print s
            }
        ' "$list_file" 2>/dev/null | tr '\n' ' ')
    fi
    if [ -z "$(printf '%s' "$ctrl_ids" | tr -d '[:space:]')" ] && [ "$RAID_HAS_ARCCONF" -eq 1 ]; then
        ctrl_ids="1"
    fi
    if [ -n "$(printf '%s' "$ctrl_ids" | tr -d '[:space:]')" ]; then
        collect_arcconf_multi "storage.raid_arcconf_config" "storage/raid-arcconf-config.log" "$bin" \
            "${dbin} GETCONFIG <N> AL" "config" "$ctrl_ids"
        collect_arcconf_multi "storage.raid_arcconf_status" "storage/raid-arcconf-status.log" "$bin" \
            "${dbin} GETSTATUS <N>" "status" "$ctrl_ids"
        collect_arcconf_multi "storage.raid_arcconf_logs" "storage/raid-arcconf-logs.log" "$bin" \
            "${dbin} GETLOGS <N> DEAD/DEVICE/EVENT" "logs" "$ctrl_ids"
    fi
}

collect_ssacli() {
    local bin="$1"
    local dbin
    dbin=$(logical_bin_path "$bin")
    run_raid_cmd "storage.raid_ssacli_status" "storage/raid-ssacli-status.log" "$dbin" \
        "${dbin} ctrl all show status" "" "ctrl_zero" -- "$bin" ctrl all show status
    run_raid_cmd "storage.raid_ssacli_config" "storage/raid-ssacli-config.log" "$dbin" \
        "${dbin} ctrl all show config detail" "" "ctrl_zero" -- "$bin" ctrl all show config detail
    run_raid_cmd "storage.raid_ssacli_detail" "storage/raid-ssacli-detail.log" "$dbin" \
        "${dbin} ctrl all show detail" "" "ctrl_zero" -- "$bin" ctrl all show detail
}

collect_sasircu() {
    local tag="$1"
    local bin="$2"
    local dbin
    dbin=$(logical_bin_path "$bin")
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local combined="${SCRATCH_DIR}/${tag}_combined.tmp"
    local sub_raw="${SCRATCH_DIR}/${tag}_sub.tmp"
    : > "$combined"
    : > "$sub_raw"

    local rc=0
    ( cd "$SCRATCH_DIR" && exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_raw" "$bin" LIST ) || rc=$?
    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local st
    st=$(classify_cmd_status "$rc" "true" "$CMD_TIMEOUT_SEC" "$sub_raw" 0 "$elapsed_ms")
    printf '## %s LIST\n' "$dbin" >> "$combined"
    cat "$sub_raw" >> "$combined"
    printf '\n' >> "$combined"

    local cids=""
    if [ "$st" = "ok" ]; then
        cids=$(awk '/^[[:space:]]+[0-9]+[[:space:]]+[A-Za-z0-9]/ { if (!seen[$1]++) print $1 }' "$sub_raw" 2>/dev/null | tr '\n' ' ')
        local cid
        for cid in $cids; do
            local sub_cmd
            for sub_cmd in DISPLAY STATUS; do
                : > "$sub_raw"
                ( cd "$SCRATCH_DIR" && exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_raw" "$bin" "$cid" "$sub_cmd" ) || true
                printf '## %s %s %s\n' "$dbin" "$cid" "$sub_cmd" >> "$combined"
                cat "$sub_raw" >> "$combined"
                printf '\n' >> "$combined"
            done
        done
    fi

    local note=""
    if grep -qiE 'no lsi sas|no adapters found|no controller' "$combined" 2>/dev/null && [ -z "$(printf '%s' "$cids" | tr -d '[:space:]')" ]; then
        st="not_applicable"
        note="no matching SAS controller detected by ${tag}"
    elif [ "$st" = "permission_denied" ]; then
        note="requires root privileges (uid=${RUN_AS_UID})"
    elif [ "$st" = "timeout" ]; then
        note="timed out after ${CMD_TIMEOUT_SEC}s"
    fi

    finalize_item "storage.raid_${tag}" "storage" "storage/raid-${tag}.log" "composite" \
        "${dbin} LIST; ${dbin} <N> DISPLAY; ${dbin} <N> STATUS" "$dbin" "" \
        "true" "$item_start_iso" "$item_start_ms" "$rc" "$st" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$combined" "$note"
}

collect_smartctl_megaraid_fallback() {
    local smart_bin="$1"
    local dbin
    dbin=$(logical_bin_path "$smart_bin")
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local combined="${SCRATCH_DIR}/smart_megaraid_combined.tmp"
    local sub_tmp="${SCRATCH_DIR}/smart_megaraid_sub.tmp"
    local targets_tmp="${SCRATCH_DIR}/smart_megaraid_targets.tmp"
    : > "$combined"
    : > "$sub_tmp"
    : > "$targets_tmp"

    # Discover one representative device per MegaRAID SCSI host (never hardcode /dev/sda).
    local scsi_host_dir="${ROOT_PREFIX}/sys/class/scsi_host"
    if [ -d "$scsi_host_dir" ]; then
        local shost pname bdir bdev
        for shost in "$scsi_host_dir"/host*; do
            [ -r "$shost/proc_name" ] || continue
            pname=$(tr -d '[:space:]' < "$shost/proc_name" 2>/dev/null || true)
            case "$pname" in
                megaraid_sas|megaraid_mbox|megaraid_mm)
                    bdev=""
                    for bdir in "$shost"/device/target*/*/block/*; do
                        [ -d "$bdir" ] || continue
                        bdev="/dev/$(basename "$bdir")"
                        break
                    done
                    if [ -n "$bdev" ]; then
                        printf '%s\n' "$bdev" >> "$targets_tmp"
                    fi ;;
            esac
        done
    fi
    if [ ! -s "$targets_tmp" ] && command -v lsblk >/dev/null 2>&1; then
        lsblk -dn -o NAME,TYPE,MODEL 2>/dev/null \
            | awk '$2=="disk" && tolower($0) ~ /(mr[0-9]|perc|megaraid|serveraid|avago|lsi|smc)/ { print "/dev/" $1; exit }' >> "$targets_tmp" || true
    fi
    if [ ! -s "$targets_tmp" ]; then
        if [ -e "${ROOT_PREFIX}/dev/bus/0" ]; then
            printf '/dev/bus/0\n' >> "$targets_tmp"
        elif command -v lsblk >/dev/null 2>&1; then
            lsblk -dn -o NAME,TYPE,TRAN 2>/dev/null \
                | awk '$2=="disk" && tolower($3)!="fc" && tolower($3)!="iscsi" && $1 ~ /^sd/ { print "/dev/" $1; exit }' >> "$targets_tmp" || true
        elif [ -b /dev/sda ]; then
            printf '/dev/sda\n' >> "$targets_tmp"
        fi
    fi

    if [ ! -s "$targets_tmp" ]; then
        finalize_item "storage.raid_smartctl_megaraid" "storage" "storage/raid-smartctl-megaraid.log" "composite" \
            "${dbin} -H -i -A -l error -d megaraid,<N> <dev>" "$dbin" "" "true" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "true" "false" "$combined" "no MegaRAID host block device found for smartctl passthrough"
        return 0
    fi
    LC_ALL=C sort -u "$targets_tmp" | head -n 4 > "${targets_tmp}.uniq" && mv "${targets_tmp}.uniq" "$targets_tmp"

    local max_did="${ITCHECK_MEGARAID_MAX_DID:-63}"
    if ! is_pos_int "$max_did"; then
        max_did=63
    elif [ "$max_did" -gt 255 ]; then
        max_did=255
    fi

    local budget_sec="$CMD_TIMEOUT_SEC"
    [ "$budget_sec" -lt 10 ] && budget_sec=10
    local budget_ms=$((budget_sec * 1000))
    local found_any=0 budget_hit=0 cidx=0 dev_path
    while IFS= read -r dev_path; do
        [ -n "$dev_path" ] || continue
        local did=0 found_ctrl=0 consec_miss=0 rc=0 elapsed_ms=0
        while [ "$did" -le "$max_did" ]; do
            elapsed_ms=$(( $(now_ms) - item_start_ms ))
            if [ "$elapsed_ms" -ge "$budget_ms" ]; then
                budget_hit=1
                break
            fi
            : > "$sub_tmp"
            rc=0
            exec_with_timeout 5 "$sub_tmp" "$smart_bin" -H -i -A -l error -d "megaraid,${did}" "$dev_path" || rc=$?
            if [ "$rc" -ne 124 ] && [ -s "$sub_tmp" ] && grep -qiE '^(Vendor:|Product:|Device Model:|Model Number:|Device type:|SMART Health Status:|SMART overall-health self-assessment)' "$sub_tmp" 2>/dev/null; then
                printf '## smartctl -H -i -A -l error -d megaraid,%s %s (controller=%s)\n' "$did" "$dev_path" "$cidx" >> "$combined"
                cat "$sub_tmp" >> "$combined"
                printf '\n' >> "$combined"
                found_any=$((found_any + 1))
                found_ctrl=$((found_ctrl + 1))
                consec_miss=0
            else
                if [ "$found_ctrl" -gt 0 ]; then
                    consec_miss=$((consec_miss + 1))
                    if [ "$did" -ge 32 ] && [ "$consec_miss" -ge 16 ]; then
                        break
                    fi
                fi
            fi
            did=$((did + 1))
        done
        cidx=$((cidx + 1))
        [ "$budget_hit" -eq 1 ] && break
    done < "$targets_tmp"

    local status="empty" final_rc=0 note=""
    if [ "$found_any" -gt 0 ]; then
        status="ok"
        [ "$budget_hit" -eq 1 ] && note="stopped probing after ${CMD_TIMEOUT_SEC}s budget (${found_any} devices captured)"
    elif [ "$budget_hit" -eq 1 ]; then
        status="timeout"
        final_rc=124
        note="smartctl megaraid probe timed out after ${CMD_TIMEOUT_SEC}s"
    else
        status="empty"
        note="no physical drives or enclosures responded via smartctl -d megaraid"
    fi

    finalize_item "storage.raid_smartctl_megaraid" "storage" "storage/raid-smartctl-megaraid.log" "composite" \
        "${dbin} -H -i -A -l error -d megaraid,<N> <dev> (fallback without StorCLI/PercCLI/MegaCLI)" "$dbin" "" "true" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$combined" "$note"
}

collect_raid_tools() {
    # MegaRAID family: prefer PercCLI on Dell PERC, otherwise StorCLI, falling back to MegaCLI.
    local mega_ran=""
    if [ "$RAID_HAS_DELL_PERC" -eq 1 ] && [ -n "$RAID_BIN_PERCCLI" ]; then
        collect_storcli_family "perccli" "$RAID_BIN_PERCCLI"
        mega_ran="perccli"
    elif [ -n "$RAID_BIN_STORCLI" ]; then
        collect_storcli_family "storcli" "$RAID_BIN_STORCLI"
        mega_ran="storcli"
    elif [ -n "$RAID_BIN_PERCCLI" ]; then
        collect_storcli_family "perccli" "$RAID_BIN_PERCCLI"
        mega_ran="perccli"
    elif [ -n "$RAID_BIN_MEGACLI" ]; then
        collect_megacli "$RAID_BIN_MEGACLI"
        mega_ran="megacli"
    fi
    # Legacy Gen1 fallback: if StorCLI/PercCLI found 0 controllers while MegaCLI is also installed, run MegaCLI.
    if [ -n "$mega_ran" ] && [ "$mega_ran" != "megacli" ] && [ -n "$RAID_BIN_MEGACLI" ]; then
        local sa_file="${CFGDIR}/storage/raid-${mega_ran}-show-all.log"
        if [ -r "$sa_file" ] && grep -qiE 'number of controllers[[:space:]]*=[[:space:]]*0|\[not applicable:' "$sa_file" 2>/dev/null; then
            collect_megacli "$RAID_BIN_MEGACLI"
            mega_ran="megacli"
        fi
    fi

    # Check whether any MegaRAID CLI actually captured controller details.
    local mega_ok=0
    if [ -n "$mega_ran" ]; then
        local mega_chk_file="${CFGDIR}/storage/raid-${mega_ran}-show-all.log"
        [ "$mega_ran" = "megacli" ] && mega_chk_file="${CFGDIR}/storage/raid-megacli-adpallinfo.log"
        if [ -r "$mega_chk_file" ] && ! grep -qiE 'number of controllers[[:space:]]*=[[:space:]]*0|\[not applicable:|\[permission denied:|\[command failed' "$mega_chk_file" 2>/dev/null; then
            mega_ok=1
        fi
    fi
    # Fallback: when a MegaRAID/PERC controller is present without a working MegaRAID CLI,
    # probe physical drives and enclosures via smartctl -d megaraid,<N> (root + smartctl required).
    if [ "$RAID_HAS_MEGARAID" -eq 1 ] && [ "$mega_ok" -eq 0 ] && [ "$IS_ROOT" = "true" ] && [ -n "$RAID_BIN_SMARTCTL" ]; then
        collect_smartctl_megaraid_fallback "$RAID_BIN_SMARTCTL"
    fi

    [ -n "$RAID_BIN_ARCCONF" ]  && collect_arcconf "$RAID_BIN_ARCCONF"
    [ -n "$RAID_BIN_SSACLI" ]   && collect_ssacli "$RAID_BIN_SSACLI"
    [ -n "$RAID_BIN_SAS3IRCU" ] && collect_sasircu "sas3ircu" "$RAID_BIN_SAS3IRCU"
    [ -n "$RAID_BIN_SAS2IRCU" ] && collect_sasircu "sas2ircu" "$RAID_BIN_SAS2IRCU"
}

run_perf_cmd() {
    local item_id="$1" rel_path="$2" display_cmd="$3"
    shift 3
    if [ "$SKIP_PERF" = "1" ]; then
        local item_start_iso item_start_ms empty_file="${SCRATCH_DIR}/skip_empty.tmp"
        item_start_iso=$(iso_now_raw)
        item_start_ms=$(now_ms)
        : > "$empty_file"
        finalize_item "$item_id" "performance" "$rel_path" "command" "$display_cmd" "$1" "" \
            "false" "$item_start_iso" "$item_start_ms" -1 "skipped" "$PERF_TIMEOUT_SEC" \
            "false" "false" "$empty_file" "skipped via --skip-perf"
        return 0
    fi
    run_cmd "$item_id" "performance" "$rel_path" "command" "false" "$PERF_TIMEOUT_SEC" "false" "none" "" "$display_cmd" -- "$@"
}

# ── v2.3.0 Read-Only Collectors: Environment, Tuning, Enterprise Storage, Security & PSI ──

collect_virt() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/virt.tmp"
    local sub_tmp="${SCRATCH_DIR}/virt_sub.tmp"
    : > "$out_file"
    : > "$sub_tmp"

    local sdv_raw="unavailable" sdv_rc=-1
    local dockerenv="false" containerenv="false"
    local p1_env="none" p1_cg="none" vz_flag="false" wsl_flag="false"
    local virt_type="none" virt_kind="bare_metal" is_container="false" virt_source="none"

    # Under ITCHECK_ROOT without ITCHECK_KEEP_PATH=1, skip host systemd-detect-virt to preserve sandbox isolation.
    if command -v systemd-detect-virt >/dev/null 2>&1 && { [ -z "$ROOT_PREFIX" ] || [ "${ITCHECK_KEEP_PATH:-0}" = "1" ]; }; then
        sdv_rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" systemd-detect-virt || sdv_rc=$?
        if [ "$sdv_rc" -ne 124 ] && [ -s "$sub_tmp" ]; then
            sdv_raw=$(head -n 1 "$sub_tmp" | tr 'A-Z' 'a-z' | tr -cd 'a-z0-9._-')
            [ -z "$sdv_raw" ] && sdv_raw="unknown"
        elif [ "$sdv_rc" -eq 1 ]; then
            sdv_raw="none"
        fi
    fi

    [ -f "${ROOT_PREFIX}/.dockerenv" ] && dockerenv="true"
    [ -f "${ROOT_PREFIX}/run/.containerenv" ] && containerenv="true"

    # Extract ONLY container=<val> from /proc/1/environ; never inspect or emit any other env var.
    local p1_env_file="${ROOT_PREFIX}/proc/1/environ"
    if [ -r "$p1_env_file" ]; then
        local cval=""
        cval=$(tr '\0' '\n' < "$p1_env_file" 2>/dev/null \
            | awk -F= '$1=="container" { v=substr($0, 11); gsub(/[^A-Za-z0-9._-]/, "", v); print tolower(substr(v, 1, 48)); exit }' || true)
        [ -n "$cval" ] && p1_env="$cval"
    fi

    local p1_cg_file="${ROOT_PREFIX}/proc/1/cgroup"
    if [ -r "$p1_cg_file" ]; then
        local cgval=""
        cgval=$(awk '
            tolower($0) ~ /kubepods/ { print "kubepods"; exit }
            tolower($0) ~ /docker/ { print "docker"; exit }
            tolower($0) ~ /containerd/ { print "containerd"; exit }
            tolower($0) ~ /(podman|libpod)/ { print "podman"; exit }
            tolower($0) ~ /\/lxc[\/.-]/ { print "lxc"; exit }
            tolower($0) ~ /systemd-nspawn/ { print "systemd-nspawn"; exit }
        ' "$p1_cg_file" 2>/dev/null || true)
        [ -n "$cgval" ] && p1_cg="$cgval"
    fi

    if [ -d "${ROOT_PREFIX}/proc/vz" ] && [ ! -d "${ROOT_PREFIX}/proc/bc" ]; then
        vz_flag="true"
    fi

    local pver_file="${ROOT_PREFIX}/proc/version"
    if [ -r "$pver_file" ] && grep -qiE 'microsoft|wsl' "$pver_file" 2>/dev/null; then
        wsl_flag="true"
    fi

    # Resolve primary virtualization/container identity: explicit container signals take precedence.
    if [ "$dockerenv" = "true" ]; then
        virt_type="docker"; virt_kind="container"; is_container="true"; virt_source="dockerenv"
    elif [ "$containerenv" = "true" ]; then
        virt_type="podman"; virt_kind="container"; is_container="true"; virt_source="containerenv"
    elif [ "$p1_env" != "none" ]; then
        virt_type="$p1_env"; virt_kind="container"; is_container="true"; virt_source="proc1_environ"
    elif [ "$p1_cg" != "none" ]; then
        virt_type="$p1_cg"; virt_kind="container"; is_container="true"; virt_source="proc1_cgroup"
    elif [ "$vz_flag" = "true" ]; then
        virt_type="openvz"; virt_kind="container"; is_container="true"; virt_source="proc_vz"
    elif [ "$wsl_flag" = "true" ]; then
        virt_type="wsl"; virt_kind="container"; is_container="true"; virt_source="proc_version"
    elif [ "$sdv_raw" != "unavailable" ] && [ "$sdv_raw" != "unknown" ]; then
        virt_type="$sdv_raw"
        virt_source="systemd-detect-virt"
        case "$sdv_raw" in
            none)
                virt_kind="bare_metal"; is_container="false" ;;
            docker|podman|lxc|lxc-libvirt|openvz|rkt|wsl|systemd-nspawn|container-other|kubepods|containerd|crio|proot|pouch)
                virt_kind="container"; is_container="true" ;;
            *)
                virt_kind="vm"; is_container="false" ;;
        esac
    else
        # Fallback: sysfs hypervisor / DMI product / /proc/cpuinfo hypervisor flag
        local hyp_file="${ROOT_PREFIX}/sys/hypervisor/type"
        if [ -r "$hyp_file" ]; then
            local ht=""
            ht=$(tr -d '[:space:]' < "$hyp_file" 2>/dev/null | tr 'A-Z' 'a-z' || true)
            if [ -n "$ht" ]; then
                virt_type="$ht"; virt_kind="vm"; virt_source="sys_hypervisor"
            fi
        fi
        if [ "$virt_type" = "none" ]; then
            local dmi_str="" dmi_f
            for dmi_f in "${ROOT_PREFIX}/sys/class/dmi/id/product_name" "${ROOT_PREFIX}/sys/class/dmi/id/sys_vendor" "${ROOT_PREFIX}/sys/class/dmi/id/bios_vendor"; do
                [ -r "$dmi_f" ] || continue
                dmi_str="${dmi_str} $(tr -d '\r\n' < "$dmi_f" 2>/dev/null || true)"
            done
            local dmi_low
            dmi_low=$(printf '%s' "$dmi_str" | tr 'A-Z' 'a-z')
            case "$dmi_low" in
                *vmware*) virt_type="vmware"; virt_kind="vm"; virt_source="dmi" ;;
                *kvm*|*qemu*|*bochs*|*openstack*) virt_type="kvm"; virt_kind="vm"; virt_source="dmi" ;;
                *virtualbox*|*innotek*) virt_type="oracle"; virt_kind="vm"; virt_source="dmi" ;;
                *microsoft*virtual*|*hyper-v*) virt_type="microsoft"; virt_kind="vm"; virt_source="dmi" ;;
                *xen*) virt_type="xen"; virt_kind="vm"; virt_source="dmi" ;;
                *amazon*ec2*) virt_type="amazon"; virt_kind="vm"; virt_source="dmi" ;;
                *google*compute*) virt_type="google"; virt_kind="vm"; virt_source="dmi" ;;
                *alibaba*cloud*) virt_type="kvm"; virt_kind="vm"; virt_source="dmi" ;;
                *bhyve*) virt_type="bhyve"; virt_kind="vm"; virt_source="dmi" ;;
                *parallels*) virt_type="parallels"; virt_kind="vm"; virt_source="dmi" ;;
            esac
        fi
        if [ "$virt_type" = "none" ] && [ -r "${ROOT_PREFIX}/proc/cpuinfo" ]; then
            if grep -qE '^flags[[:space:]]*:.*[[:space:]]hypervisor([[:space:]]|$)' "${ROOT_PREFIX}/proc/cpuinfo" 2>/dev/null; then
                virt_type="vm-other"; virt_kind="vm"; virt_source="cpuinfo_hypervisor_flag"
            fi
        fi
    fi

    {
        printf 'virt=%s\n' "$virt_type"
        printf 'virt_kind=%s\n' "$virt_kind"
        printf 'is_container=%s\n' "$is_container"
        printf 'virt_source=%s\n' "$virt_source"
        printf 'systemd_detect_virt=%s\n' "$sdv_raw"
        printf 'dockerenv_present=%s\n' "$dockerenv"
        printf 'containerenv_present=%s\n' "$containerenv"
        printf 'proc1_container_env=%s\n' "$p1_env"
        printf 'proc1_cgroup_container=%s\n' "$p1_cg"
        printf 'wsl_detected=%s\n' "$wsl_flag"
    } > "$out_file"

    finalize_item "system.virt" "system" "system/virt.log" "composite" \
        "systemd-detect-virt; container markers (/.dockerenv, /run/.containerenv, /proc/1/environ[container=], /proc/1/cgroup)" \
        "systemd-detect-virt,/.dockerenv,/proc/1/environ" "" "false" \
        "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
        "false" "true" "$out_file" ""
}

collect_ntp_sync() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/ntp_sync.tmp"
    local sub_tmp="${SCRATCH_DIR}/ntp_sync_sub.tmp"
    : > "$out_file"

    local any_tool=0 any_data=0 timeout_any=0 rc=0

    if command -v chronyc >/dev/null 2>&1; then
        any_tool=1
        : > "$sub_tmp"
        rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" chronyc -n tracking || rc=$?
        printf 'chronyc_tracking_rc=%s\n' "$rc" >> "$out_file"
        printf '## chronyc -n tracking\n' >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
        if [ "$rc" -eq 124 ]; then
            timeout_any=1
        else
            any_data=1
        fi
        if [ "$rc" -eq 0 ]; then
            : > "$sub_tmp"
            local src_rc=0
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" chronyc -n sources || src_rc=$?
            printf '## chronyc -n sources\n' >> "$out_file"
            cat "$sub_tmp" >> "$out_file"
            printf '\n' >> "$out_file"
        fi
    fi

    if command -v ntpstat >/dev/null 2>&1; then
        any_tool=1
        : > "$sub_tmp"
        rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" ntpstat || rc=$?
        printf 'ntpstat_rc=%s\n' "$rc" >> "$out_file"
        printf '## ntpstat\n' >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
        if [ "$rc" -eq 124 ]; then
            timeout_any=1
        else
            any_data=1
        fi
    fi

    if command -v ntpq >/dev/null 2>&1; then
        any_tool=1
        : > "$sub_tmp"
        rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" ntpq -pn || rc=$?
        printf 'ntpq_rc=%s\n' "$rc" >> "$out_file"
        printf '## ntpq -pn\n' >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
        if [ "$rc" -eq 124 ]; then
            timeout_any=1
        else
            any_data=1
        fi
    fi

    local status="ok" final_rc=0 note=""
    if [ "$any_tool" -eq 0 ]; then
        status="not_applicable"; final_rc=-1; note="chronyc, ntpstat and ntpq not installed"
    elif [ "$any_data" -eq 0 ] && [ "$timeout_any" -eq 1 ]; then
        status="timeout"; final_rc=124; note="NTP sync command timed out after ${CMD_TIMEOUT_SEC}s"
    fi

    finalize_item "system.ntp_sync" "system" "system/ntp-sync.log" "composite" \
        "chronyc -n tracking; chronyc -n sources; ntpstat; ntpq -pn" "chronyc,ntpstat,ntpq" "" "false" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "false" "$out_file" "$note"
}

collect_tuned() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/tuned_raw.tmp"
    local out_file="${SCRATCH_DIR}/tuned.tmp"
    : > "$raw_out"
    : > "$out_file"

    if ! command -v tuned-adm >/dev/null 2>&1; then
        finalize_item "system.tuned" "system" "system/tuned.log" "command" \
            "tuned-adm active" "tuned-adm" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" "tuned-adm not installed"
        return 0
    fi

    local rc=0
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" tuned-adm active || rc=$?
    local status="ok" final_rc=0 note=""
    if [ "$rc" -eq 124 ]; then
        status="timeout"; final_rc=124; note="timed out after ${CMD_TIMEOUT_SEC}s"
        cp "$raw_out" "$out_file"
    elif [ "$IS_ROOT" != "true" ] && [ "$rc" -ne 0 ] && is_permission_error_text "$raw_out"; then
        status="permission_denied"; final_rc="$rc"; note="requires root privileges (uid=${RUN_AS_UID})"
        cp "$raw_out" "$out_file"
    else
        {
            printf 'tuned_adm_rc=%s\n' "$rc"
            cat "$raw_out"
        } > "$out_file"
        status="ok"; final_rc=0
    fi

    finalize_item "system.tuned" "system" "system/tuned.log" "command" \
        "tuned-adm active" "tuned-adm" "" "false" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "false" "$out_file" "$note"
}

collect_thp_hugepages() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/thp_hugepages.tmp"
    : > "$out_file"

    local found=0
    local thp_base="${ROOT_PREFIX}/sys/kernel/mm/transparent_hugepage"
    [ -d "$thp_base" ] || thp_base="${ROOT_PREFIX}/sys/kernel/mm/redhat_transparent_hugepage"

    if [ -r "${thp_base}/enabled" ]; then
        found=1
        printf 'thp_enabled=%s\n' "$(tr -d '\r\n' < "${thp_base}/enabled" 2>/dev/null || true)" >> "$out_file"
    fi
    if [ -r "${thp_base}/defrag" ]; then
        found=1
        printf 'thp_defrag=%s\n' "$(tr -d '\r\n' < "${thp_base}/defrag" 2>/dev/null || true)" >> "$out_file"
    fi
    if [ -r "${thp_base}/shmem_enabled" ]; then
        found=1
        printf 'thp_shmem_enabled=%s\n' "$(tr -d '\r\n' < "${thp_base}/shmem_enabled" 2>/dev/null || true)" >> "$out_file"
    fi

    local meminfo_file="${ROOT_PREFIX}/proc/meminfo"
    if [ -r "$meminfo_file" ]; then
        local hp_lines=""
        hp_lines=$(grep -iE '^(AnonHugePages|ShmemHugePages|FileHugePages|HugePages_Total|HugePages_Free|HugePages_Rsvd|HugePages_Surp|Hugepagesize|Hugetlb):' "$meminfo_file" 2>/dev/null || true)
        if [ -n "$hp_lines" ]; then
            found=1
            printf '\n## /proc/meminfo (HugePages)\n' >> "$out_file"
            printf '%s\n' "$hp_lines" >> "$out_file"
        fi
    fi

    if [ "$found" -eq 0 ]; then
        finalize_item "system.thp_hugepages" "system" "system/thp-hugepages.log" "composite" \
            "cat /sys/kernel/mm/transparent_hugepage/{enabled,defrag}; grep HugePages /proc/meminfo" \
            "/sys/kernel/mm/transparent_hugepage,/proc/meminfo" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" "THP sysfs and HugePages meminfo entries not available"
    else
        finalize_item "system.thp_hugepages" "system" "system/thp-hugepages.log" "composite" \
            "cat /sys/kernel/mm/transparent_hugepage/{enabled,defrag}; grep HugePages /proc/meminfo" \
            "/sys/kernel/mm/transparent_hugepage,/proc/meminfo" "" "false" \
            "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" ""
    fi
}

collect_apparmor() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/apparmor.tmp"
    local sub_tmp="${SCRATCH_DIR}/apparmor_sub.tmp"
    : > "$out_file"

    local mod_file="${ROOT_PREFIX}/sys/module/apparmor/parameters/enabled"
    local sec_dir="${ROOT_PREFIX}/sys/kernel/security/apparmor"
    local aa_bin=""
    if command -v aa-status >/dev/null 2>&1; then
        aa_bin="aa-status"
    elif command -v apparmor_status >/dev/null 2>&1; then
        aa_bin="apparmor_status"
    fi

    if [ ! -e "$mod_file" ] && [ ! -d "$sec_dir" ] && [ -z "$aa_bin" ]; then
        finalize_item "system.apparmor" "system" "system/apparmor.log" "composite" \
            "AppArmor sysfs & aa-status" "/sys/module/apparmor,aa-status" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" "AppArmor not present on this host"
        return 0
    fi

    local mod_val="unknown" sec_present="absent" has_sysfs=0
    if [ -r "$mod_file" ]; then
        mod_val=$(tr -d '[:space:]' < "$mod_file" 2>/dev/null || echo "unknown")
        has_sysfs=1
    fi
    if [ -d "$sec_dir" ]; then
        sec_present="present"
        has_sysfs=1
    fi

    printf 'apparmor_module_enabled=%s\n' "$mod_val" >> "$out_file"
    printf 'apparmor_securityfs=%s\n' "$sec_present" >> "$out_file"

    local status="ok" final_rc=0 note=""
    if [ -n "$aa_bin" ]; then
        : > "$sub_tmp"
        local rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" "$aa_bin" || rc=$?
        printf 'aa_status_rc=%s\n' "$rc" >> "$out_file"
        if [ "$rc" -eq 124 ]; then
            if [ "$has_sysfs" -eq 0 ]; then
                status="timeout"; final_rc=124; note="${aa_bin} timed out after ${CMD_TIMEOUT_SEC}s"
            fi
        elif [ "$IS_ROOT" != "true" ] && [ "$rc" -ne 0 ] && is_permission_error_text "$sub_tmp"; then
            printf 'aa_status_note=permission_denied\n' >> "$out_file"
            if [ "$has_sysfs" -eq 0 ]; then
                status="permission_denied"; final_rc="$rc"; note="${aa_bin} requires root privileges (uid=${RUN_AS_UID})"
            fi
        else
            printf '## %s\n' "$aa_bin" >> "$out_file"
            cat "$sub_tmp" >> "$out_file"
            printf '\n' >> "$out_file"
        fi
    fi

    finalize_item "system.apparmor" "system" "system/apparmor.log" "composite" \
        "AppArmor sysfs & aa-status" "/sys/module/apparmor,aa-status" "" "false" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "false" "$out_file" "$note"
}

# Recursive Include-aware sshd_config reader (read-only, stops at Match, depth<=8).
# Emits normalized "key value" lines to $2; updates visited file list $3 and counters.
_sshd_walk_file() {
    local cfg_path="$1"
    local raw_kv="$2"
    local visited_file="$3"
    local depth="$4"

    [ "$depth" -le 8 ] || return 0
    [ -f "$cfg_path" ] && [ -r "$cfg_path" ] || return 0
    if grep -Fxq "$cfg_path" "$visited_file" 2>/dev/null; then
        return 0
    fi
    printf '%s\n' "$cfg_path" >> "$visited_file"
    SSHD_WALKED_FILES=$((SSHD_WALKED_FILES + 1))

    local line clean key rest inc_pat full_pat inc_f
    while IFS= read -r line || [ -n "$line" ]; do
        # Strip CR and comments
        line="${line%$'\r'}"
        clean="${line%%#*}"
        # Trim leading/trailing whitespace using awk-free bash builtins
        clean="${clean#"${clean%%[![:space:]]*}"}"
        clean="${clean%"${clean##*[![:space:]]}"}"
        [ -n "$clean" ] || continue

        # Support both "Key Value" and "Key=Value"
        if [[ "$clean" == *=* ]] && [[ "${clean%%=*}" != *[[:space:]]* ]]; then
            key="${clean%%=*}"
            rest="${clean#*=}"
        else
            key="${clean%%[[:space:]]*}"
            rest="${clean#"$key"}"
        fi
        rest="${rest#"${rest%%[![:space:]]*}"}"
        key=$(printf '%s' "$key" | tr 'A-Z' 'a-z')
        [ -n "$key" ] || continue

        if [ "$key" = "match" ]; then
            SSHD_MATCH_PRESENT="true"
            break
        fi
        if [ "$key" = "include" ]; then
            # Expand each whitespace-separated glob pattern in order (OpenSSH first-match semantics)
            local old_noglob=0
            case "$-" in *f*) old_noglob=1 ;; esac
            set +f
            for inc_pat in $rest; do
                [ -n "$inc_pat" ] || continue
                case "$inc_pat" in
                    /*) full_pat="${ROOT_PREFIX}${inc_pat}" ;;
                    *)  full_pat="${ROOT_PREFIX}/etc/ssh/${inc_pat}" ;;
                esac
                local matched_list="${SCRATCH_DIR}/sshd_inc_${depth}.tmp"
                : > "$matched_list"
                for inc_f in $full_pat; do
                    [ -f "$inc_f" ] && printf '%s\n' "$inc_f" >> "$matched_list"
                done
                if [ -s "$matched_list" ]; then
                    LC_ALL=C sort -u "$matched_list" > "${matched_list}.s" && mv "${matched_list}.s" "$matched_list"
                    while IFS= read -r inc_f; do
                        [ -n "$inc_f" ] || continue
                        _sshd_walk_file "$inc_f" "$raw_kv" "$visited_file" $((depth + 1))
                    done < "$matched_list"
                fi
                rm -f "$matched_list" 2>/dev/null || true
            done
            [ "$old_noglob" -eq 1 ] && set -f
            continue
        fi
        printf '%s %s\n' "$key" "$rest" >> "$raw_kv"
    done < "$cfg_path"
}

# Strict security-policy whitelist filter for both `sshd -T` and Include-aware sshd_config parsing.
# NEVER emits HostKey, Banner, AuthorizedKeys*, user/group lists, or any secret/path content.
_sshd_filter_whitelist() {
    local src_file="$1"
    local dst_file="$2"
    awk '
    BEGIN {
        wl["permitrootlogin"] = 1
        wl["passwordauthentication"] = 1
        wl["pubkeyauthentication"] = 1
        wl["kbdinteractiveauthentication"] = 1
        wl["challengeresponseauthentication"] = 1
        wl["permitemptypasswords"] = 1
        wl["protocol"] = 1
        wl["x11forwarding"] = 1
        wl["maxauthtries"] = 1
        wl["logingracetime"] = 1
        wl["usepam"] = 1
        wl["allowtcpforwarding"] = 1
        wl["permituserenvironment"] = 1
        wl["clientaliveinterval"] = 1
        wl["clientalivecountmax"] = 1

        cnt_wl["allowusers"] = 1
        cnt_wl["allowgroups"] = 1
        cnt_wl["denyusers"] = 1
        cnt_wl["denygroups"] = 1

        port_list = ""
    }
    {
        if (NF < 2) next
        k = tolower($1)
        if (k == "port") {
            p = $2
            if (p ~ /^[0-9]+$/ && !seen_port[p]++) {
                port_list = (port_list == "" ? p : port_list "," p)
            }
            next
        }
        if (k in wl) {
            if (!(k in val)) {
                v = tolower($2)
                gsub(/[^a-z0-9._-]/, "", v)
                if (v != "") val[k] = v
            }
            next
        }
        if (k in cnt_wl) {
            c[k] += (NF - 1)
            next
        }
    }
    END {
        order[1] = "port"
        order[2] = "protocol"
        order[3] = "permitrootlogin"
        order[4] = "passwordauthentication"
        order[5] = "pubkeyauthentication"
        order[6] = "kbdinteractiveauthentication"
        order[7] = "challengeresponseauthentication"
        order[8] = "permitemptypasswords"
        order[9] = "x11forwarding"
        order[10] = "maxauthtries"
        order[11] = "logingracetime"
        order[12] = "usepam"
        order[13] = "allowtcpforwarding"
        order[14] = "permituserenvironment"
        order[15] = "clientaliveinterval"
        order[16] = "clientalivecountmax"
        if (port_list != "") val["port"] = port_list
        for (i = 1; i <= 16; i++) {
            k = order[i]
            if (k in val) printf "%s=%s\n", k, val[k]
        }
        c_order[1] = "allowusers"
        c_order[2] = "allowgroups"
        c_order[3] = "denyusers"
        c_order[4] = "denygroups"
        for (i = 1; i <= 4; i++) {
            k = c_order[i]
            printf "%s_count=%d\n", k, (k in c ? c[k] : 0)
        }
    }' "$src_file" > "$dst_file"
}

collect_sshd_effective() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_tmp="${SCRATCH_DIR}/sshd_raw.tmp"
    local filt_tmp="${SCRATCH_DIR}/sshd_filt.tmp"
    local visited_tmp="${SCRATCH_DIR}/sshd_visited.tmp"
    local out_file="${SCRATCH_DIR}/sshd_effective.tmp"
    : > "$raw_tmp"
    : > "$filt_tmp"
    : > "$visited_tmp"
    : > "$out_file"

    local cfg_file="${ROOT_PREFIX}/etc/ssh/sshd_config"
    local has_sshd_bin=0
    if command -v sshd >/dev/null 2>&1 && { [ -z "$ROOT_PREFIX" ] || [ "${ITCHECK_KEEP_PATH:-0}" = "1" ]; }; then
        has_sshd_bin=1
    fi

    if [ "$has_sshd_bin" -eq 0 ] && [ ! -e "$cfg_file" ]; then
        finalize_item "system.sshd_effective" "system" "system/sshd-effective.log" "composite" \
            "sshd -T (whitelist policy keys only) / Include-aware /etc/ssh/sshd_config" \
            "sshd,/etc/ssh/sshd_config" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "true" "true" "$out_file" "sshd and /etc/ssh/sshd_config not present"
        return 0
    fi

    local source_used="" status="ok" final_rc=0 note=""
    SSHD_WALKED_FILES=0
    SSHD_MATCH_PRESENT="false"

    # Prefer `sshd -T` when running as root and sshd binary is available.
    if [ "$IS_ROOT" = "true" ] && [ "$has_sshd_bin" -eq 1 ]; then
        local rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_tmp" sshd -T || rc=$?
        if [ "$rc" -ne 0 ] && [ "$rc" -ne 124 ] && grep -qiE 'match|connection parameter|-C' "$raw_tmp" 2>/dev/null; then
            : > "$raw_tmp"
            rc=0
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_tmp" sshd -T -C "user=root,host=localhost,addr=127.0.0.1" || rc=$?
        fi
        if [ "$rc" -eq 0 ] && [ -s "$raw_tmp" ]; then
            _sshd_filter_whitelist "$raw_tmp" "$filt_tmp"
            if grep -qE '^(permitrootlogin|passwordauthentication|pubkeyauthentication|port)=' "$filt_tmp" 2>/dev/null; then
                source_used="sshd -T"
            fi
        fi
    fi

    # Fallback (non-root or sshd -T unavailable/failed): Include-aware recursive parse of /etc/ssh/sshd_config.
    if [ -z "$source_used" ]; then
        if [ ! -e "$cfg_file" ]; then
            if [ "$IS_ROOT" != "true" ]; then
                status="permission_denied"; final_rc=1; note="sshd -T requires root and /etc/ssh/sshd_config not present"
            else
                status="not_applicable"; final_rc=-1; note="/etc/ssh/sshd_config not present"
            fi
        elif [ ! -r "$cfg_file" ]; then
            status="permission_denied"; final_rc=1; note="cannot read /etc/ssh/sshd_config (uid=${RUN_AS_UID})"
        else
            : > "$raw_tmp"
            : > "$visited_tmp"
            _sshd_walk_file "$cfg_file" "$raw_tmp" "$visited_tmp" 0
            _sshd_filter_whitelist "$raw_tmp" "$filt_tmp"
            source_used="sshd_config_include_parse"
        fi
    fi

    if [ "$status" = "ok" ]; then
        {
            printf 'source=%s\n' "$source_used"
            printf 'included_files_count=%s\n' "$SSHD_WALKED_FILES"
            printf 'match_blocks_present=%s\n' "$SSHD_MATCH_PRESENT"
            cat "$filt_tmp"
        } > "$out_file"
    fi

    finalize_item "system.sshd_effective" "system" "system/sshd-effective.log" "composite" \
        "sshd -T (whitelist policy keys only) / Include-aware /etc/ssh/sshd_config" \
        "sshd,/etc/ssh/sshd_config" "" "false" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "true" "$out_file" "$note"
}

collect_uid0_sudo() {
    # Strictly read-only /etc/passwd + sudo/wheel group membership; NEVER reads password hashes.
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/uid0_sudo.tmp"
    local sub_tmp="${SCRATCH_DIR}/uid0_grp.tmp"
    : > "$out_file"

    local passwd_file="${ROOT_PREFIX}/etc/passwd"
    if [ ! -e "$passwd_file" ]; then
        finalize_item "system.uid0_sudo" "system" "system/uid0-sudo.log" "composite" \
            "UID=0 check (/etc/passwd) & getent group sudo wheel" "/etc/passwd,/etc/group" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "true" "true" "$out_file" "/etc/passwd not present"
        return 0
    fi
    if [ ! -r "$passwd_file" ]; then
        finalize_item "system.uid0_sudo" "system" "system/uid0-sudo.log" "composite" \
            "UID=0 check (/etc/passwd) & getent group sudo wheel" "/etc/passwd,/etc/group" "" "false" \
            "$item_start_iso" "$item_start_ms" 1 "permission_denied" "$CMD_TIMEOUT_SEC" \
            "true" "true" "$out_file" "cannot read /etc/passwd (uid=${RUN_AS_UID})"
        return 0
    fi

    awk -F: '
    BEGIN { total = 0; extra = 0; all_s = ""; extra_s = "" }
    $1 !~ /^[[:space:]]*#/ && NF >= 3 && $3 == "0" && $1 != "" {
        u = $1
        gsub(/[^A-Za-z0-9._-]/, "", u)
        if (u == "") next
        total++
        all_s = (all_s == "" ? u : all_s "," u)
        if (u != "root") {
            extra++
            extra_s = (extra_s == "" ? u : extra_s "," u)
        }
    }
    END {
        printf "account_source=/etc/passwd\n"
        printf "uid0_total_count=%d\n", total
        printf "uid0_extra_count=%d\n", extra
        printf "uid0_accounts=%s\n", (all_s == "" ? "none" : all_s)
        printf "uid0_extra_accounts=%s\n", (extra_s == "" ? "none" : extra_s)
    }' "$passwd_file" > "$out_file"

    local grp_file="${ROOT_PREFIX}/etc/group"
    local gname gline members gpresent
    for gname in sudo wheel; do
        gline=""
        gpresent="false"
        members="none"
        if [ -n "$ROOT_PREFIX" ] && [ -r "$grp_file" ]; then
            gline=$(awk -F: -v g="$gname" '$1==g { print $0; exit }' "$grp_file" 2>/dev/null || true)
        elif command -v getent >/dev/null 2>&1 && [ -z "$ROOT_PREFIX" ]; then
            : > "$sub_tmp"
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" getent group "$gname" || true
            gline=$(head -n 1 "$sub_tmp" 2>/dev/null || true)
        elif [ -r "$grp_file" ]; then
            gline=$(awk -F: -v g="$gname" '$1==g { print $0; exit }' "$grp_file" 2>/dev/null || true)
        fi
        if [ -n "$gline" ]; then
            gpresent="true"
            members=$(printf '%s\n' "$gline" | awk -F: '{ m=$4; gsub(/[[:space:]]/, "", m); print (m == "" ? "none" : m) }')
        fi
        printf '%s_group_present=%s\n' "$gname" "$gpresent" >> "$out_file"
        printf '%s_group_members=%s\n' "$gname" "$members" >> "$out_file"
    done

    finalize_item "system.uid0_sudo" "system" "system/uid0-sudo.log" "composite" \
        "UID=0 check (/etc/passwd) & getent group sudo wheel" "/etc/passwd,/etc/group" "" "false" \
        "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
        "true" "true" "$out_file" ""
}

collect_numa() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/numa.tmp"
    local sub_tmp="${SCRATCH_DIR}/numa_sub.tmp"
    : > "$out_file"

    local any_src=0 timeout_any=0 ok_any=0
    if command -v numactl >/dev/null 2>&1; then
        any_src=1
        : > "$sub_tmp"
        local rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" numactl --hardware || rc=$?
        if [ "$rc" -eq 124 ]; then
            timeout_any=1
        elif [ "$rc" -eq 0 ] && [ -s "$sub_tmp" ]; then
            ok_any=1
            printf '## numactl --hardware\n' >> "$out_file"
            cat "$sub_tmp" >> "$out_file"
            printf '\n' >> "$out_file"
        fi
    fi

    local node_root="${ROOT_PREFIX}/sys/devices/system/node"
    if [ -d "$node_root" ]; then
        local sys_tmp="${SCRATCH_DIR}/numa_sysfs.tmp"
        : > "$sys_tmp"
        local node_found=0 ndir nid cpulist dist mem_tot mem_free
        for ndir in "$node_root"/node[0-9]*; do
            [ -d "$ndir" ] || continue
            node_found=1
            nid=$(basename "$ndir")
            cpulist=$(tr -d '\r\n' < "$ndir/cpulist" 2>/dev/null || true)
            dist=$(tr -d '\r\n' < "$ndir/distance" 2>/dev/null || true)
            mem_tot=""
            mem_free=""
            if [ -r "$ndir/meminfo" ]; then
                mem_tot=$(awk '/MemTotal:/ { sub(/^.*MemTotal:[[:space:]]*/, ""); print $1; exit }' "$ndir/meminfo" 2>/dev/null || true)
                mem_free=$(awk '/MemFree:/ { sub(/^.*MemFree:[[:space:]]*/, ""); print $1; exit }' "$ndir/meminfo" 2>/dev/null || true)
            fi
            printf 'node=%s | cpulist=%s | mem_total_kb=%s | mem_free_kb=%s | distance=%s\n' \
                "$nid" "$cpulist" "$mem_tot" "$mem_free" "$dist" >> "$sys_tmp"
        done
        if [ "$node_found" -eq 1 ]; then
            any_src=1
            ok_any=1
            printf '## /sys/devices/system/node\n' >> "$out_file"
            cat "$sys_tmp" >> "$out_file"
            printf '\n' >> "$out_file"
        fi
    fi

    local status="ok" final_rc=0 note=""
    if [ "$any_src" -eq 0 ] || [ "$ok_any" -eq 0 ]; then
        if [ "$timeout_any" -eq 1 ]; then
            status="timeout"; final_rc=124; note="numactl timed out after ${CMD_TIMEOUT_SEC}s"
        else
            status="not_applicable"; final_rc=-1; note="numactl and /sys/devices/system/node not available"
        fi
    fi

    finalize_item "hardware.numa" "hardware" "hardware/numa.log" "composite" \
        "numactl --hardware; /sys/devices/system/node" "numactl,/sys/devices/system/node" "" "false" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "false" "$out_file" "$note"
}

collect_io_scheduler() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/io_scheduler.tmp"
    : > "$out_file"

    local blk_root="${ROOT_PREFIX}/sys/block"
    local found=0 count=0 bname bdir sched active ra rot nr_req
    if [ -d "$blk_root" ]; then
        while IFS= read -r bname; do
            [ -n "$bname" ] || continue
            case "$bname" in
                loop*|ram*|sr*|fd*|zram*|nbd*) continue ;;
            esac
            bdir="${blk_root}/${bname}"
            [ -d "${bdir}/queue" ] || continue
            if [ ! -r "${bdir}/queue/scheduler" ] && [ ! -r "${bdir}/queue/read_ahead_kb" ]; then
                continue
            fi
            found=1
            count=$((count + 1))
            [ "$count" -gt 128 ] && break
            sched=""
            active=""
            if [ -r "${bdir}/queue/scheduler" ]; then
                sched=$(tr -d '\r\n' < "${bdir}/queue/scheduler" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' || true)
                active=$(printf '%s\n' "$sched" | awk '{ if (match($0, /\[[^]]+\]/)) print substr($0, RSTART+1, RLENGTH-2); else print $1 }')
            fi
            ra=$(tr -d '[:space:]' < "${bdir}/queue/read_ahead_kb" 2>/dev/null || true)
            rot=$(tr -d '[:space:]' < "${bdir}/queue/rotational" 2>/dev/null || true)
            nr_req=$(tr -d '[:space:]' < "${bdir}/queue/nr_requests" 2>/dev/null || true)
            printf 'device=%s | active=%s | scheduler=%s | read_ahead_kb=%s | rotational=%s | nr_requests=%s\n' \
                "$bname" "$active" "$sched" "$ra" "$rot" "$nr_req" >> "$out_file"
        done < <(ls -1 "$blk_root" 2>/dev/null | LC_ALL=C sort)
    fi

    if [ "$found" -eq 0 ]; then
        finalize_item "storage.io_scheduler" "storage" "storage/io-scheduler.log" "sysfs" \
            "/sys/block/*/queue/{scheduler,read_ahead_kb,rotational,nr_requests}" "/sys/block" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" "no block device queue attributes present under /sys/block"
    else
        finalize_item "storage.io_scheduler" "storage" "storage/io-scheduler.log" "sysfs" \
            "/sys/block/*/queue/{scheduler,read_ahead_kb,rotational,nr_requests}" "/sys/block" "" "false" \
            "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" ""
    fi
}

collect_nvme_smart() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/nvme_smart.tmp"
    local sub_tmp="${SCRATCH_DIR}/nvme_sub.tmp"
    local devs_tmp="${SCRATCH_DIR}/nvme_devs.tmp"
    : > "$out_file"
    : > "$devs_tmp"

    # Discover NVMe devices while strictly honoring ROOT_PREFIX isolation.
    local sys_nvme="${ROOT_PREFIX}/sys/class/nvme"
    local ndir nname
    if [ -d "$sys_nvme" ]; then
        for ndir in "$sys_nvme"/nvme[0-9]*; do
            [ -e "$ndir" ] || continue
            nname=$(basename "$ndir")
            printf '/dev/%s\n' "$nname" >> "$devs_tmp"
        done
    fi
    if [ ! -s "$devs_tmp" ]; then
        local dev_entry dbase
        for dev_entry in "${ROOT_PREFIX}"/dev/nvme[0-9]*; do
            [ -e "$dev_entry" ] || continue
            dbase=$(basename "$dev_entry")
            case "$dbase" in
                nvme[0-9]|nvme[0-9][0-9]) printf '/dev/%s\n' "$dbase" >> "$devs_tmp" ;;
            esac
        done
        if [ ! -s "$devs_tmp" ]; then
            for dev_entry in "${ROOT_PREFIX}"/dev/nvme[0-9]*n[0-9]*; do
                [ -e "$dev_entry" ] || continue
                dbase=$(basename "$dev_entry")
                case "$dbase" in
                    *p[0-9]*) continue ;;
                    *) printf '/dev/%s\n' "$dbase" >> "$devs_tmp" ;;
                esac
            done
        fi
    fi
    if [ ! -s "$devs_tmp" ] && [ -z "$ROOT_PREFIX" ] && command -v lsblk >/dev/null 2>&1; then
        lsblk -dn -o NAME,TYPE 2>/dev/null \
            | awk '$2=="disk" && $1 ~ /^nvme[0-9]+n[0-9]+$/ { sub(/n[0-9]+$/, "", $1); print "/dev/" $1 }' >> "$devs_tmp" || true
    fi

    if [ ! -s "$devs_tmp" ]; then
        finalize_item "storage.nvme_smart" "storage" "storage/nvme-smart.log" "composite" \
            "nvme list; nvme smart-log /dev/nvme*" "nvme,/sys/class/nvme" "" "true" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "true" "false" "$out_file" "no NVMe devices present"
        return 0
    fi

    LC_ALL=C sort -u "$devs_tmp" | head -n 32 > "${devs_tmp}.u" && mv "${devs_tmp}.u" "$devs_tmp"

    if ! command -v nvme >/dev/null 2>&1; then
        finalize_item "storage.nvme_smart" "storage" "storage/nvme-smart.log" "composite" \
            "nvme list; nvme smart-log /dev/nvme*" "nvme,/sys/class/nvme" "" "true" \
            "$item_start_iso" "$item_start_ms" 127 "command_missing" "$CMD_TIMEOUT_SEC" \
            "true" "false" "$out_file" "NVMe devices detected but nvme CLI not installed"
        return 0
    fi

    local ok_any=0 perm_any=0 timeout_any=0 last_rc=0 rc=0 elapsed_ms=0 sub_start_ms=0
    : > "$sub_tmp"
    sub_start_ms=$(now_ms)
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" nvme list || rc=$?
    elapsed_ms=$(( $(now_ms) - sub_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local st
    st=$(classify_cmd_status "$rc" "true" "$CMD_TIMEOUT_SEC" "$sub_tmp" 0 "$elapsed_ms")
    last_rc="$rc"
    printf '## nvme list\n' >> "$out_file"
    cat "$sub_tmp" >> "$out_file"
    printf '\n' >> "$out_file"
    case "$st" in
        ok|empty) ok_any=1 ;;
        permission_denied) perm_any=1 ;;
        timeout) timeout_any=1 ;;
    esac

    local dev_path
    while IFS= read -r dev_path; do
        [ -n "$dev_path" ] || continue
        : > "$sub_tmp"
        sub_start_ms=$(now_ms)
        rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" nvme smart-log "$dev_path" || rc=$?
        elapsed_ms=$(( $(now_ms) - sub_start_ms ))
        [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
        st=$(classify_cmd_status "$rc" "true" "$CMD_TIMEOUT_SEC" "$sub_tmp" 0 "$elapsed_ms")
        last_rc="$rc"
        printf '## nvme smart-log %s\n' "$dev_path" >> "$out_file"
        cat "$sub_tmp" >> "$out_file"
        printf '\n' >> "$out_file"
        case "$st" in
            ok|empty) ok_any=1 ;;
            permission_denied) perm_any=1 ;;
            timeout) timeout_any=1 ;;
        esac
    done < "$devs_tmp"

    local status="failed" final_rc="$last_rc" note=""
    if [ "$timeout_any" -eq 1 ] && [ "$ok_any" -eq 0 ]; then
        status="timeout"; final_rc=124; note="nvme command timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$ok_any" -eq 1 ]; then
        status="ok"; final_rc=0
    elif [ "$perm_any" -eq 1 ]; then
        status="permission_denied"; note="nvme smart-log requires root privileges (uid=${RUN_AS_UID})"
    fi

    finalize_item "storage.nvme_smart" "storage" "storage/nvme-smart.log" "composite" \
        "nvme list; nvme smart-log /dev/nvme*" "nvme,/sys/class/nvme" "" "true" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "false" "$out_file" "$note"
}

collect_fc_host() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/fc_host.tmp"
    : > "$out_file"

    local fc_root="${ROOT_PREFIX}/sys/class/fc_host"
    local found=0 hname hdir attr val
    if [ -d "$fc_root" ]; then
        while IFS= read -r hname; do
            case "$hname" in
                host[0-9]*) ;;
                *) continue ;;
            esac
            hdir="${fc_root}/${hname}"
            [ -d "$hdir" ] || continue
            found=1
            printf '## /sys/class/fc_host/%s\n' "$hname" >> "$out_file"
            printf 'host=%s\n' "$hname" >> "$out_file"
            for attr in port_state speed supported_speeds port_name node_name port_type symbolic_name fabric_name port_id maxframe_size; do
                if [ -r "${hdir}/${attr}" ]; then
                    val=$(tr -d '\r\n' < "${hdir}/${attr}" 2>/dev/null || true)
                    printf '%s=%s\n' "$attr" "$val" >> "$out_file"
                fi
            done
            if [ -d "${hdir}/statistics" ]; then
                for attr in link_failure_count loss_of_sync_count loss_of_signal_count invalid_crc_count invalid_tx_word_count error_frames dumped_frames nos_count prim_seq_protocol_err_count rx_frames tx_frames fcp_input_megabytes fcp_output_megabytes; do
                    if [ -r "${hdir}/statistics/${attr}" ]; then
                        val=$(tr -d '[:space:]' < "${hdir}/statistics/${attr}" 2>/dev/null || true)
                        printf 'stat.%s=%s\n' "$attr" "$val" >> "$out_file"
                    fi
                done
            fi
            printf '\n' >> "$out_file"
        done < <(ls -1 "$fc_root" 2>/dev/null | LC_ALL=C sort)
    fi

    if [ "$found" -eq 0 ]; then
        finalize_item "storage.fc_host" "storage" "storage/fc-host.log" "sysfs" \
            "/sys/class/fc_host/host*/{port_state,speed,port_name,statistics/*}" "/sys/class/fc_host" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" "no Fibre Channel HBA present under /sys/class/fc_host"
    else
        finalize_item "storage.fc_host" "storage" "storage/fc-host.log" "sysfs" \
            "/sys/class/fc_host/host*/{port_state,speed,port_name,statistics/*}" "/sys/class/fc_host" "" "false" \
            "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" ""
    fi
}

collect_tcp_states() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_out="${SCRATCH_DIR}/tcp_states_raw.tmp"
    local out_file="${SCRATCH_DIR}/tcp_states.tmp"
    : > "$raw_out"
    : > "$out_file"

    local src_cmd="" src_bin="" rc=0
    if command -v ss >/dev/null 2>&1; then
        src_bin="ss"
        src_cmd="ss -Htan"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" ss -Htan || rc=$?
    elif command -v netstat >/dev/null 2>&1; then
        src_bin="netstat"
        src_cmd="netstat -tan"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_out" netstat -tan || rc=$?
    else
        finalize_item "network.tcp_states" "network" "network/tcp-states.log" "command" \
            "ss -Htan (TCP socket state summary)" "ss,netstat" "" "false" \
            "$item_start_iso" "$item_start_ms" 127 "command_missing" "$CMD_TIMEOUT_SEC" \
            "false" "true" "$out_file" "neither ss nor netstat installed"
        return 0
    fi

    local elapsed_ms=$(( $(now_ms) - item_start_ms ))
    [ "$elapsed_ms" -lt 0 ] && elapsed_ms=0
    local status note=""
    status=$(classify_cmd_status "$rc" "false" "$CMD_TIMEOUT_SEC" "$raw_out" 0 "$elapsed_ms")
    if [ "$status" = "ok" ] || [ "$status" = "empty" ]; then
        awk -v src="$src_cmd" '
        function norm_state(s) {
            u = toupper(s)
            if (u == "ESTABLISHED") return "ESTAB"
            if (u == "SYN_SENT") return "SYN-SENT"
            if (u == "SYN_RECV") return "SYN-RECV"
            if (u == "FIN_WAIT1") return "FIN-WAIT-1"
            if (u == "FIN_WAIT2") return "FIN-WAIT-2"
            if (u == "TIME_WAIT") return "TIME-WAIT"
            if (u == "CLOSE_WAIT") return "CLOSE-WAIT"
            if (u == "LAST_ACK") return "LAST-ACK"
            if (u ~ /^(LISTEN|ESTAB|SYN-SENT|SYN-RECV|FIN-WAIT-1|FIN-WAIT-2|TIME-WAIT|CLOSE-WAIT|LAST-ACK|CLOSING|CLOSED|CLOSE|UNCONN)$/) return u
            return ""
        }
        BEGIN { total = 0 }
        /^[[:space:]]*$/ { next }
        /^(Netid|State|Proto|Active)[[:space:]]/ { next }
        {
            st = norm_state($1)
            if (st == "" && NF >= 2) st = norm_state($2)
            if (st == "" && NF >= 6) st = norm_state($6)
            if (st != "") {
                cnt[st]++
                total++
            }
        }
        END {
            printf "source=%s\n", src
            printf "total=%d\n", total
            ord[1] = "LISTEN"; ord[2] = "ESTAB"; ord[3] = "SYN-SENT"; ord[4] = "SYN-RECV"
            ord[5] = "TIME-WAIT"; ord[6] = "CLOSE-WAIT"; ord[7] = "FIN-WAIT-1"; ord[8] = "FIN-WAIT-2"
            ord[9] = "LAST-ACK"; ord[10] = "CLOSING"; ord[11] = "CLOSE"
            for (i = 1; i <= 11; i++) {
                k = ord[i]
                printf "%s=%d\n", k, (k in cnt ? cnt[k] : 0)
            }
        }' "$raw_out" > "$out_file"
        status="ok"
        rc=0
    else
        [ "$status" = "timeout" ] && note="timed out after ${CMD_TIMEOUT_SEC}s"
        cp "$raw_out" "$out_file"
    fi

    finalize_item "network.tcp_states" "network" "network/tcp-states.log" "command" \
        "ss -Htan (TCP socket state summary)" "$src_bin" "" "false" \
        "$item_start_iso" "$item_start_ms" "$rc" "$status" "$CMD_TIMEOUT_SEC" \
        "false" "true" "$out_file" "$note"
}

collect_kdump() {
    # Lists kdump service state & /var/crash metadata ONLY; NEVER reads vmcore memory dumps.
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/kdump.tmp"
    local sub_tmp="${SCRATCH_DIR}/kdump_sub.tmp"
    : > "$out_file"

    local svc_name="kdump" svc_enabled="unknown" svc_active="unknown"
    if command -v systemctl >/dev/null 2>&1; then
        local cand en_val act_val
        for cand in kdump kdump-tools; do
            : > "$sub_tmp"
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" systemctl is-enabled "$cand" || true
            en_val=$(head -n 1 "$sub_tmp" 2>/dev/null | tr -d '\r')
            case "$en_val" in
                enabled|disabled|static|indirect|masked|generated|enabled-runtime|alias|linked)
                    svc_name="$cand"
                    svc_enabled="$en_val"
                    : > "$sub_tmp"
                    exec_with_timeout "$CMD_TIMEOUT_SEC" "$sub_tmp" systemctl is-active "$cand" || true
                    act_val=$(head -n 1 "$sub_tmp" 2>/dev/null | tr -d '\r')
                    case "$act_val" in
                        active|inactive|failed|activating|deactivating|reloading|unknown)
                            svc_active="$act_val" ;;
                    esac
                    break ;;
            esac
        done
    fi

    local kexec_loaded="unavailable" kexec_size="unavailable"
    if [ -r "${ROOT_PREFIX}/sys/kernel/kexec_crash_loaded" ]; then
        kexec_loaded=$(tr -d '[:space:]' < "${ROOT_PREFIX}/sys/kernel/kexec_crash_loaded" 2>/dev/null || echo "unavailable")
    fi
    if [ -r "${ROOT_PREFIX}/sys/kernel/kexec_crash_size" ]; then
        kexec_size=$(tr -d '[:space:]' < "${ROOT_PREFIX}/sys/kernel/kexec_crash_size" 2>/dev/null || echo "unavailable")
    fi

    local crash_dir="${ROOT_PREFIX}/var/crash"
    local crash_exists="false" crash_count=0
    local entries_tmp="${SCRATCH_DIR}/kdump_entries.tmp"
    : > "$entries_tmp"

    if [ -d "$crash_dir" ]; then
        crash_exists="true"
        local entry ename etype mtime has_vmcore vmcore_bytes has_dmesg
        while IFS= read -r ename; do
            [ -n "$ename" ] || continue
            # Skip non-crash placeholder/helper files
            case "$ename" in
                scripts|.keep|kexec_cmd|README*) continue ;;
            esac
            entry="${crash_dir}/${ename}"
            [ -e "$entry" ] || continue
            if [ -d "$entry" ]; then
                etype="dir"
            else
                etype="file"
            fi
            mtime=""
            if command -v stat >/dev/null 2>&1; then
                mtime=$(stat -c '%y' "$entry" 2>/dev/null | awk '{print $1 " " substr($2, 1, 8)}' || true)
            fi
            if [ -z "$mtime" ]; then
                mtime=$(ls -ld "$entry" 2>/dev/null | awk '{print $6 " " $7 " " $8}' || true)
            fi
            has_vmcore="false"
            vmcore_bytes=0
            has_dmesg="false"
            if [ "$etype" = "dir" ]; then
                if [ -f "${entry}/vmcore" ]; then
                    has_vmcore="true"
                    vmcore_bytes=$(file_size_bytes "${entry}/vmcore")
                    [ -z "$vmcore_bytes" ] && vmcore_bytes=0
                fi
                if [ -f "${entry}/vmcore-dmesg.txt" ] || [ -f "${entry}/dmesg.txt" ]; then
                    has_dmesg="true"
                fi
            elif [[ "$ename" == *.crash ]] || [[ "$ename" == *.dump ]] || [[ "$ename" == vmcore* ]]; then
                has_vmcore="true"
                vmcore_bytes=$(file_size_bytes "$entry")
                [ -z "$vmcore_bytes" ] && vmcore_bytes=0
            else
                continue
            fi
            crash_count=$((crash_count + 1))
            [ "$crash_count" -le 50 ] && printf 'entry=%s | type=%s | mtime=%s | has_vmcore=%s | vmcore_bytes=%s | has_dmesg=%s\n' \
                "$ename" "$etype" "$mtime" "$has_vmcore" "$vmcore_bytes" "$has_dmesg" >> "$entries_tmp"
        done < <(ls -1 "$crash_dir" 2>/dev/null | LC_ALL=C sort)
    fi

    {
        printf 'service_name=%s\n' "$svc_name"
        printf 'service_enabled=%s\n' "$svc_enabled"
        printf 'service_active=%s\n' "$svc_active"
        printf 'kexec_crash_loaded=%s\n' "$kexec_loaded"
        printf 'kexec_crash_size=%s\n' "$kexec_size"
        printf 'crash_dir=/var/crash\n'
        printf 'crash_dir_exists=%s\n' "$crash_exists"
        printf 'crash_dump_count=%s\n' "$crash_count"
        printf '\n## crash_entries\n'
        if [ -s "$entries_tmp" ]; then
            cat "$entries_tmp"
        else
            printf 'none\n'
        fi
    } > "$out_file"

    finalize_item "logs.kdump" "logs" "logs/kdump.log" "composite" \
        "systemctl is-enabled/is-active kdump; /var/crash metadata listing (no dump content read)" \
        "systemctl,/var/crash" "" "false" \
        "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
        "false" "true" "$out_file" ""
}

collect_ssh_auth_failures() {
    # OpenSSH <9.8 (sshd) & >=9.8 (sshd-session) 24h auth failure counters ONLY; never outputs usernames, raw log lines, or source IPs.
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local raw_tmp="${SCRATCH_DIR}/ssh_auth_raw.tmp"
    local out_file="${SCRATCH_DIR}/ssh_auth_failures.tmp"
    : > "$raw_tmp"
    : > "$out_file"

    local src_used="" status="ok" final_rc=0 note="" perm_hit=0 timeout_hit=0

    # Under ITCHECK_ROOT with sandbox auth.log/secure, read sandbox files directly for deterministic tests.
    local f real_f
    if [ -n "$ROOT_PREFIX" ]; then
        for f in /var/log/auth.log /var/log/secure; do
            real_f="${ROOT_PREFIX}${f}"
            if [ -e "$real_f" ]; then
                if [ -r "$real_f" ]; then
                    tail -n 5000 "$real_f" >> "$raw_tmp" 2>/dev/null || true
                    src_used="${src_used:+${src_used},}${f}"
                else
                    perm_hit=1
                fi
            fi
        done
    fi

    if [ -z "$src_used" ] && command -v journalctl >/dev/null 2>&1; then
        local rc=0
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_tmp" \
            journalctl --since=-24h -t sshd -t sshd-session --no-pager -o short-iso || rc=$?
        if [ "$rc" -eq 124 ]; then
            timeout_hit=1
        elif [ "$rc" -ne 0 ] && grep -qiE 'invalid option|unrecognized option|unknown option' "$raw_tmp" 2>/dev/null; then
            : > "$raw_tmp"
            rc=0
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$raw_tmp" \
                journalctl --since=-24h -u sshd -u ssh --no-pager -o short-iso || rc=$?
            [ "$rc" -eq 124 ] && timeout_hit=1
        fi
        if [ "$rc" -eq 0 ]; then
            if [ "$IS_ROOT" != "true" ] && grep -qiE 'No journal files were opened due to insufficient permissions|You are currently not seeing messages from other users and the system' "$raw_tmp" 2>/dev/null; then
                perm_hit=1
                : > "$raw_tmp"
            else
                src_used="journalctl"
            fi
        elif [ "$IS_ROOT" != "true" ] && is_permission_error_text "$raw_tmp"; then
            perm_hit=1
            : > "$raw_tmp"
        fi
    fi

    # Fallback to /var/log/auth.log and /var/log/secure if journalctl did not supply readable data.
    if [ -z "$src_used" ]; then
        for f in /var/log/auth.log /var/log/secure; do
            real_f="${ROOT_PREFIX}${f}"
            [ -e "$real_f" ] || continue
            if [ -r "$real_f" ]; then
                tail -n 5000 "$real_f" >> "$raw_tmp" 2>/dev/null || true
                src_used="${src_used:+${src_used},}${f}"
            else
                perm_hit=1
            fi
        done
    fi

    if [ -z "$src_used" ]; then
        if [ "$timeout_hit" -eq 1 ]; then
            status="timeout"; final_rc=124; note="journalctl ssh auth query timed out after ${CMD_TIMEOUT_SEC}s"
        elif [ "$perm_hit" -eq 1 ]; then
            status="permission_denied"; final_rc=1; note="insufficient permissions to read sshd journal or auth log (uid=${RUN_AS_UID})"
        else
            status="not_applicable"; final_rc=-1; note="no journalctl or /var/log/{auth.log,secure} source available"
        fi
    else
        awk -v src="$src_used" '
        BEGIN {
            fp = 0; inv = 0; fpk = 0; maxa = 0; pam = 0; disc = 0
            sshd_hits = 0; sess_hits = 0; uniq_ip = 0
        }
        /(sshd|sshd-session)(\[[0-9]+\])?:/ {
            hit = 0
            if ($0 ~ /Failed password for/) { fp++; hit = 1 }
            else if ($0 ~ /Invalid user /) { inv++; hit = 1 }
            else if ($0 ~ /Failed publickey for/) { fpk++; hit = 1 }
            else if ($0 ~ /maximum authentication attempts exceeded/) { maxa++; hit = 1 }
            else if ($0 ~ /pam_unix\(sshd:auth\):[[:space:]]*authentication failure/) { pam++; hit = 1 }
            else if ($0 ~ /Disconnected from (authenticating|invalid) user/) { disc++; hit = 1 }
            if (hit) {
                if ($0 ~ /sshd-session(\[[0-9]+\])?:/) sess_hits++
                else sshd_hits++
                if (match($0, /from[[:space:]]+[0-9a-fA-F.:]+/)) {
                    ip = substr($0, RSTART, RLENGTH)
                    sub(/^from[[:space:]]+/, "", ip)
                    if (ip != "" && !seen_ip[ip]++) uniq_ip++
                }
            }
        }
        END {
            total = fp + inv + fpk + maxa + pam
            printf "source=%s\n", src
            printf "window=24h\n"
            printf "identifiers=sshd,sshd-session\n"
            printf "failed_auth_total=%d\n", total
            printf "failed_password_count=%d\n", fp
            printf "invalid_user_count=%d\n", inv
            printf "failed_publickey_count=%d\n", fpk
            printf "max_auth_exceeded_count=%d\n", maxa
            printf "pam_auth_failure_count=%d\n", pam
            printf "disconnected_auth_count=%d\n", disc
            printf "unique_source_ip_count=%d\n", uniq_ip
            printf "sshd_tag_hits=%d\n", sshd_hits
            printf "sshd_session_tag_hits=%d\n", sess_hits
        }' "$raw_tmp" > "$out_file"
        status="ok"; final_rc=0
    fi

    finalize_item "logs.ssh_auth_failures" "logs" "logs/ssh-auth-failures.log" "composite" \
        "SSH 24h auth-failure counters (sshd + OpenSSH 9.8+ sshd-session; aggregated counts only)" \
        "journalctl,/var/log/auth.log,/var/log/secure" "" "false" \
        "$item_start_iso" "$item_start_ms" "$final_rc" "$status" "$CMD_TIMEOUT_SEC" \
        "true" "true" "$out_file" "$note"
}

collect_psi() {
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/psi.tmp"
    : > "$out_file"

    local psi_dir="${ROOT_PREFIX}/proc/pressure"
    local found=0 res pfile
    if [ -d "$psi_dir" ]; then
        for res in cpu memory io; do
            pfile="${psi_dir}/${res}"
            [ -r "$pfile" ] || continue
            found=1
            printf '## /proc/pressure/%s\n' "$res" >> "$out_file"
            cat "$pfile" >> "$out_file" 2>/dev/null || true
            printf '\n' >> "$out_file"
        done
    fi

    if [ "$found" -eq 0 ]; then
        finalize_item "performance.psi" "performance" "performance/psi.log" "proc" \
            "cat /proc/pressure/{cpu,memory,io}" "/proc/pressure" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" "/proc/pressure not available on this kernel"
    else
        finalize_item "performance.psi" "performance" "performance/psi.log" "proc" \
            "cat /proc/pressure/{cpu,memory,io}" "/proc/pressure" "" "false" \
            "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
            "false" "false" "$out_file" ""
    fi
}

collect_zombies() {
    # Scans /proc/[0-9]*/stat purely with shell builtins (zero fork overhead, no TTY bias, excludes collector PID/children).
    local item_start_iso item_start_ms
    item_start_iso=$(iso_now_raw)
    item_start_ms=$(now_ms)
    local out_file="${SCRATCH_DIR}/zombies.tmp"
    local list_tmp="${SCRATCH_DIR}/zombies_list.tmp"
    : > "$out_file"
    : > "$list_tmp"

    local self_pid="$$"
    local scanned=0 z_cnt=0 d_cnt=0 listed=0
    local sf line pid after_open comm after_close state ppid
    for sf in "${ROOT_PREFIX}"/proc/[0-9]*/stat; do
        [ -r "$sf" ] || continue
        IFS= read -r line < "$sf" 2>/dev/null || continue
        case "$line" in
            *'('*')'*) ;;
            *) continue ;;
        esac
        pid="${line%% *}"
        after_open="${line#*(}"
        comm="${after_open%)*}"
        after_close="${after_open##*)}"
        # Parse state & ppid without glob expansion or spawning subshells
        set -f
        # shellcheck disable=SC2086
        set -- $after_close
        state="${1:-}"
        ppid="${2:-}"
        set +f
        # Exclude this collector and its own transient children
        if [ "$pid" = "$self_pid" ] || [ "$ppid" = "$self_pid" ]; then
            continue
        fi
        scanned=$((scanned + 1))
        if [ "$state" = "Z" ]; then
            z_cnt=$((z_cnt + 1))
            if [ "$listed" -lt 30 ]; then
                comm="${comm//|/ }"
                comm="${comm//$'\t'/ }"
                printf 'zombie=pid:%s | ppid:%s | comm:%s\n' "$pid" "$ppid" "$comm" >> "$list_tmp"
                listed=$((listed + 1))
            fi
        elif [ "$state" = "D" ]; then
            d_cnt=$((d_cnt + 1))
        fi
    done

    if [ "$scanned" -eq 0 ]; then
        finalize_item "performance.zombies" "performance" "performance/zombies.log" "proc" \
            "scan /proc/[0-9]*/stat (zombie/D-state counts & comm only)" "/proc" "" "false" \
            "$item_start_iso" "$item_start_ms" -1 "not_applicable" "$CMD_TIMEOUT_SEC" \
            "false" "true" "$out_file" "no /proc/<pid>/stat entries accessible"
        return 0
    fi

    {
        printf 'source=/proc/[0-9]*/stat\n'
        printf 'total_scanned=%s\n' "$scanned"
        printf 'zombie_count=%s\n' "$z_cnt"
        printf 'uninterruptible_d_count=%s\n' "$d_cnt"
        printf '\n## zombie_processes\n'
        if [ -s "$list_tmp" ]; then
            cat "$list_tmp"
        else
            printf 'none\n'
        fi
    } > "$out_file"

    finalize_item "performance.zombies" "performance" "performance/zombies.log" "proc" \
        "scan /proc/[0-9]*/stat (zombie/D-state counts & comm only)" "/proc" "" "false" \
        "$item_start_iso" "$item_start_ms" 0 "ok" "$CMD_TIMEOUT_SEC" \
        "false" "true" "$out_file" ""
}

# ── Section 1: system ──
echo "Collecting system information ..."
if [ -e "${ROOT_PREFIX}/etc/os-release" ] || [ ! -e "${ROOT_PREFIX}/etc/redhat-release" ]; then
    run_file "system.os_release" "system" "system/os-release.log" "file" "/etc/os-release" "false" "false" 0
else
    run_file "system.os_release" "system" "system/os-release.log" "file" "/etc/redhat-release" "false" "false" 0
fi
run_cmd  "system.uname" "system" "system/uname.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "uname -a" -- uname -a
run_cmd  "system.hostnamectl" "system" "system/hostnamectl.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "hostnamectl" -- hostnamectl
collect_virt
run_cmd  "system.uptime" "system" "system/uptime.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "uptime" -- uptime
run_cmd  "system.last_reboot" "system" "system/last-reboot.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "head:20" "" "last -x reboot | head -n 20" -- last -x reboot
run_cmd  "system.timedatectl" "system" "system/timedatectl.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "timedatectl" -- timedatectl
collect_ntp_sync
run_cmd  "system.sysctl" "system" "system/sysctl.log" "command" "false" "$CMD_TIMEOUT_SEC" "true" "none" "" "sysctl -a" -- sysctl -a
run_file "system.kernel_taint" "system" "system/kernel-taint.log" "proc" "/proc/sys/kernel/tainted" "false" "false" 0
run_file "system.file_nr" "system" "system/file-nr.log" "proc" "/proc/sys/fs/file-nr" "false" "false" 0
collect_tuned
collect_thp_hugepages
run_file "system.kernel_cmdline" "system" "system/kernel-cmdline.log" "proc" "/proc/cmdline" "false" "true" 0
run_composite_list "system.selinux" "system" "system/selinux.log" "false" "false" "getenforce; sestatus" "" -- "getenforce" "sestatus"
collect_apparmor
collect_sshd_effective
collect_uid0_sudo
collect_crontab

# ── Section 2: hardware ──
echo "Collecting hardware information ..."
run_cmd  "hardware.dmidecode" "hardware" "hardware/dmidecode.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "dmidecode" -- dmidecode
run_cmd  "hardware.model" "hardware" "hardware/model.txt" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "dmidecode -s system-product-name" -- dmidecode -s system-product-name
run_cmd  "hardware.serial" "hardware" "hardware/serial.txt" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "dmidecode -s system-serial-number" -- dmidecode -s system-serial-number
run_cmd  "hardware.bios" "hardware" "hardware/bios.txt" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "dmidecode -s bios-version" -- dmidecode -s bios-version
run_cmd  "hardware.lscpu" "hardware" "hardware/lscpu.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "lscpu" -- lscpu
run_file "hardware.cpuinfo" "hardware" "hardware/cpuinfo.log" "proc" "/proc/cpuinfo" "false" "false" 0
run_file "hardware.meminfo" "hardware" "hardware/meminfo.log" "proc" "/proc/meminfo" "false" "false" 0
collect_numa
run_cmd  "hardware.dmidecode_mem" "hardware" "hardware/dmidecode-mem.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "dmidecode -t memory" -- dmidecode -t memory
collect_lspci
run_cmd  "hardware.lsusb" "hardware" "hardware/lsusb.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "lsusb" -- lsusb
run_cmd  "hardware.lsscsi" "hardware" "hardware/lsscsi.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "lsscsi" -- lsscsi
run_cmd  "hardware.sensors" "hardware" "hardware/sensors.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "sensors" -- sensors
run_cmd  "hardware.ipmi_sel" "hardware" "hardware/ipmi-sel.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "ipmitool sel elist" -- ipmitool sel elist
run_cmd  "hardware.ipmi_sensor" "hardware" "hardware/ipmi-sensor.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "ipmitool sdr elist" -- ipmitool sdr elist
run_cmd  "hardware.ipmi_fru" "hardware" "hardware/ipmi-fru.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "ipmitool fru print" -- ipmitool fru print

# ── Section 3: storage ──
echo "Collecting storage information ..."
run_cmd  "storage.lsblk" "storage" "storage/lsblk.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "lsblk -o NAME,MODEL,SERIAL,SIZE,TYPE,FSTYPE,MOUNTPOINT,STATE,TRAN" -- lsblk -o NAME,MODEL,SERIAL,SIZE,TYPE,FSTYPE,MOUNTPOINT,STATE,TRAN
run_cmd  "storage.df" "storage" "storage/df.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "df -hT" -- df -hT
run_cmd  "storage.inode" "storage" "storage/inode.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "df -i" -- df -i
run_cmd  "storage.mount" "storage" "storage/mount.log" "command" "false" "$CMD_TIMEOUT_SEC" "true" "none" "" "mount" -- mount
run_file "storage.fstab" "storage" "storage/fstab.log" "file" "/etc/fstab" "false" "true" 0
run_cmd  "storage.fdisk" "storage" "storage/fdisk.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "fdisk -l" -- fdisk -l
run_composite_list "storage.pvs" "storage" "storage/pvs.log" "true" "false" "pvs; pvdisplay" "" -- "pvs" "pvdisplay"
run_composite_list "storage.vgs" "storage" "storage/vgs.log" "true" "false" "vgs; vgdisplay -v" "" -- "vgs" "vgdisplay -v"
run_composite_list "storage.lvs" "storage" "storage/lvs.log" "true" "false" "lvs; lvdisplay" "" -- "lvs" "lvdisplay"
run_file "storage.mdstat" "storage" "storage/mdstat.log" "proc" "/proc/mdstat" "false" "false" 0
run_cmd  "storage.mdadm" "storage" "storage/mdadm.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "mdadm --detail --scan" -- mdadm --detail --scan
run_cmd  "storage.multipath" "storage" "storage/multipath.log" "command" "true" "$CMD_TIMEOUT_SEC" "false" "none" "" "multipath -ll" -- multipath -ll
run_cmd  "storage.iscsi" "storage" "storage/iscsi.log" "command" "true" "$CMD_TIMEOUT_SEC" "true" "none" "" "iscsiadm -m session -P 3" -- iscsiadm -m session -P 3
collect_io_scheduler
collect_nvme_smart
collect_fc_host
collect_raid_detect
collect_raid_tools

if command -v lsblk >/dev/null 2>&1; then
    LSBLK_SMART_RAW=""
    if LSBLK_SMART_RAW=$(lsblk -dn -o NAME,TYPE,TRAN 2>/dev/null) && [ -n "$LSBLK_SMART_RAW" ]; then
        LSBLK_SMART_DISKS=$(printf '%s\n' "$LSBLK_SMART_RAW" | awk '$2=="disk" && tolower($3)!="fc" && tolower($3)!="iscsi"{print $1}')
    else
        LSBLK_SMART_DISKS=$(lsblk -dn -o NAME,TYPE 2>/dev/null | awk '$2=="disk"{print $1}')
    fi
    while IFS= read -r DISK; do
        [ -n "$DISK" ] || continue
        DISK_SAFE=$(sanitize_token "$DISK")
        DISK_ID=$(sanitize_id_part "$DISK")
        run_cmd "storage.smart.${DISK_ID}" "storage" "storage/smart.${DISK_SAFE}.log" "command" \
            "true" "$CMD_TIMEOUT_SEC" "false" "smart" "$DISK" \
            "smartctl -H -i -A -l error /dev/${DISK}" -- smartctl -H -i -A -l error "/dev/${DISK}"
    done <<< "$LSBLK_SMART_DISKS"
fi

# ── Section 4: network ──
echo "Collecting network information ..."
run_cmd  "network.ip_addr" "network" "network/ip-addr.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "ip addr" -- ip addr
run_composite_list "network.ip_route" "network" "network/ip-route.log" "false" "false" "ip route; ip -6 route" "" -- "ip route" "ip -6 route"
run_cmd  "network.ip_link" "network" "network/ip-link.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "ip -s link" -- ip -s link
run_file "network.resolv" "network" "network/resolv.log" "file" "/etc/resolv.conf" "false" "false" 0
run_file "network.hosts" "network" "network/hosts.log" "file" "/etc/hosts" "false" "false" 0
run_cmd  "network.listen" "network" "network/listen.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "ss -lntup" -- ss -lntup
collect_tcp_states
collect_bonding
run_composite_list "network.firewall" "network" "network/firewall.log" "true" "true" \
    "firewall-cmd --list-all; iptables -S; nft list ruleset" "" -- \
    "firewall-cmd --list-all" "iptables -S" "nft list ruleset"

SYS_NET_DIR="${ROOT_PREFIX}/sys/class/net"
if [ -d "$SYS_NET_DIR" ]; then
    while IFS= read -r NIC; do
        [ -n "$NIC" ] || continue
        [ "$NIC" = "lo" ] && continue
        NIC_SAFE=$(sanitize_token "$NIC")
        NIC_ID=$(sanitize_id_part "$NIC")
        run_composite_list "network.ethtool.${NIC_ID}" "network" "network/ethtool.${NIC_SAFE}.log" \
            "false" "false" "ethtool ${NIC}; ethtool -i ${NIC}; ethtool -S ${NIC} | head -n 80" "$NIC" -- \
            "ethtool ${NIC}" "ethtool -i ${NIC}" "ethtool -S ${NIC}|head:80"
    done < <(ls -1 "$SYS_NET_DIR" 2>/dev/null | LC_ALL=C sort)
fi

# ── Section 5: software ──
echo "Collecting software and service information ..."
run_composite_list "software.packages" "software" "software/packages.log" "false" "false" \
    "rpm -qa --last | head -n 500; dpkg -l" "" -- \
    "rpm -qa --last|head:500" "dpkg -l"
run_cmd  "software.services" "software" "software/services.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" \
    "systemctl list-units --type=service --state=running --no-pager" -- systemctl list-units --type=service --state=running --no-pager
run_cmd  "software.failed_units" "software" "software/failed-units.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" \
    "systemctl --failed --no-pager" -- systemctl --failed --no-pager
run_cmd  "software.enabled" "software" "software/enabled.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" \
    "systemctl list-unit-files --state=enabled --no-pager" -- systemctl list-unit-files --state=enabled --no-pager

# ── Section 6: logs ──
echo "Collecting error logs ..."
run_cmd "logs.dmesg_err" "logs" "logs/dmesg-err.log" "command" "false" "$CMD_TIMEOUT_SEC" "true" "tail:400" "" \
    "dmesg -T --level=emerg,alert,crit,err | tail -n 400" -- dmesg -T --level=emerg,alert,crit,err
collect_dmesg_hw
collect_journal "logs.journal_err" "logs/journal-err.log" "" 600
collect_journal "logs.journal_prev_boot" "logs/journal-prev-boot.log" "-1" 300
collect_messages_tail
collect_mcelog
collect_oom
collect_kdump
collect_ssh_auth_failures

# ── Section 7: performance ──
if [ "$SKIP_PERF" = "1" ]; then
    echo "Collecting performance snapshot (live sampling skipped) ..."
else
    echo "Collecting performance snapshot (about 45 seconds) ..."
fi
run_perf_cmd "performance.vmstat" "performance/vmstat.log" "vmstat 3 10" vmstat 3 10
run_perf_cmd "performance.iostat" "performance/iostat.log" "iostat -x 3 5" iostat -x 3 5
run_perf_cmd "performance.mpstat" "performance/mpstat.log" "mpstat -P ALL 3 3" mpstat -P ALL 3 3
run_cmd "performance.sar_today" "performance" "performance/sar-today.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "tail:60" "" "sar | tail -n 60" -- sar
run_cmd "performance.free" "performance" "performance/free.log" "command" "false" "$CMD_TIMEOUT_SEC" "false" "none" "" "free -m" -- free -m
collect_psi
collect_ps_top "performance.top10cpu" "performance/top10cpu.log" "%cpu"
collect_ps_top "performance.top10mem" "performance/top10mem.log" "%mem"
collect_ps_count
collect_zombies
collect_swap

# ── Build check.json (itcheck.linux.check/1) ──

FINISH_ISO=$(iso_now_raw)
FINISH_MS=$(now_ms)
TOTAL_DUR_MS=$((FINISH_MS - START_MS))
[ "$TOTAL_DUR_MS" -lt 0 ] && TOTAL_DUR_MS=0

if [ "$CNT_OK" -eq 0 ] && [ "$CNT_EMPTY" -eq 0 ]; then
    COLLECTION_STATUS="failed"
elif [ "$IS_ROOT" != "true" ] || [ "$CNT_PERM" -gt 0 ] || [ "$CNT_MISSING" -gt 0 ] || [ "$CNT_TIMEOUT" -gt 0 ] || [ "$CNT_FAILED" -gt 0 ] || [ "$CNT_SKIPPED" -gt 0 ]; then
    COLLECTION_STATUS="partial"
else
    COLLECTION_STATUS="complete"
fi

{
    printf '{\n'
    printf '  "schema": %s,\n' "$(printf '%s' "$SCHEMA_VERSION" | json_escape)"
    printf '  "collector": {\n'
    printf '    "name": %s,\n' "$(printf '%s' "$SCRIPT_NAME" | json_escape)"
    printf '    "version": %s,\n' "$(printf '%s' "$SCRIPT_VERSION" | json_escape)"
    printf '    "script": %s,\n' "$(printf '%s' "$SCRIPT_FILE" | json_escape)"
    printf '    "script_sha256": %s,\n' "$(printf '%s' "$SCRIPT_SELF_SHA256" | json_escape)"
    printf '    "platform": "linux"\n'
    printf '  },\n'
    printf '  "collection": {\n'
    printf '    "started_at_raw": %s,\n' "$(printf '%s' "$START_ISO" | json_escape)"
    printf '    "finished_at_raw": %s,\n' "$(printf '%s' "$FINISH_ISO" | json_escape)"
    printf '    "timezone_raw": %s,\n' "$(printf '%s' "$TZ_RAW" | json_escape)"
    printf '    "date_raw": %s,\n' "$(printf '%s' "$DATE_RAW" | json_escape)"
    printf '    "duration_ms": %s,\n' "$TOTAL_DUR_MS"
    printf '    "run_as_user": %s,\n' "$(printf '%s' "$RUN_AS_USER" | json_escape)"
    printf '    "run_as_uid": %s,\n' "$RUN_AS_UID"
    printf '    "is_root": %s,\n' "$IS_ROOT"
    printf '    "privilege_mode": %s,\n' "$(printf '%s' "$PRIVILEGE_MODE" | json_escape)"
    printf '    "command_timeout_sec": %s,\n' "$CMD_TIMEOUT_SEC"
    printf '    "perf_timeout_sec": %s,\n' "$PERF_TIMEOUT_SEC"
    printf '    "status": %s,\n' "$(printf '%s' "$COLLECTION_STATUS" | json_escape)"
    printf '    "counts": {\n'
    printf '      "total": %s,\n' "$CNT_TOTAL"
    printf '      "ok": %s,\n' "$CNT_OK"
    printf '      "empty": %s,\n' "$CNT_EMPTY"
    printf '      "permission_denied": %s,\n' "$CNT_PERM"
    printf '      "command_missing": %s,\n' "$CNT_MISSING"
    printf '      "timeout": %s,\n' "$CNT_TIMEOUT"
    printf '      "failed": %s,\n' "$CNT_FAILED"
    printf '      "not_applicable": %s,\n' "$CNT_NA"
    printf '      "skipped": %s\n' "$CNT_SKIPPED"
    printf '    }\n'
    printf '  },\n'
    printf '  "host": {\n'
    printf '    "hostname": %s,\n' "$(printf '%s' "$HOSTNAME_RAW" | json_escape)"
    printf '    "serial": %s,\n' "$(printf '%s' "$SERIAL_RAW" | json_escape)"
    printf '    "serial_source": %s,\n' "$(printf '%s' "$SERIAL_SOURCE" | json_escape)"
    printf '    "os_id": %s,\n' "$(printf '%s' "$OS_ID" | json_escape)"
    printf '    "os_pretty_name": %s,\n' "$(printf '%s' "$OS_PRETTY_NAME" | json_escape)"
    printf '    "kernel": %s,\n' "$(printf '%s' "$KERNEL_REL" | json_escape)"
    printf '    "arch": %s\n' "$(printf '%s' "$ARCH_STR" | json_escape)"
    printf '  },\n'
    printf '  "redaction": {\n'
    printf '    "applied": true,\n'
    printf '    "mode": "collector_default",\n'
    printf '    "rules": [\n'
    printf '      "ps_restricted_columns",\n'
    printf '      "crontab_metadata_only",\n'
    printf '      "cmdline_secret_mask",\n'
    printf '      "log_secret_mask",\n'
    printf '      "fstab_credential_mask",\n'
    printf '      "iscsi_chap_mask",\n'
    printf '      "raid_safe_id_mask",\n'
    printf '      "sshd_policy_whitelist",\n'
    printf '      "uid0_no_shadow",\n'
    printf '      "ssh_auth_summary_only"\n'
    printf '    ]\n'
    printf '  },\n'
    printf '  "warnings": ['
    first_w=1
    while IFS= read -r wline; do
        [ -n "$wline" ] || continue
        if [ "$first_w" -eq 0 ]; then
            printf ', '
        fi
        printf '%s' "$(printf '%s' "$wline" | json_escape)"
        first_w=0
    done < "$WARNINGS_TXT"
    printf '],\n'
    printf '  "sections": ["system", "hardware", "storage", "network", "software", "logs", "performance"],\n'
    printf '  "items": [\n'
    first_i=1
    while IFS= read -r iline; do
        [ -n "$iline" ] || continue
        if [ "$first_i" -eq 0 ]; then
            printf ',\n'
        fi
        printf '    %s' "$iline"
        first_i=0
    done < "$ITEMS_JSONL"
    printf '\n  ]\n'
    printf '}\n'
} > "${CFGDIR}/check.json"

echo "Compressing check data ..."
ARCHIVE_PATH="${OUT_DIR}/${DIRNAME}.tar.gz"
if ! tar -C "$OUT_DIR" -czf "$ARCHIVE_PATH" "$DIRNAME"; then
    echo "ERROR: failed to create archive ${ARCHIVE_PATH}" >&2
    exit 1
fi
rm -rf "$CFGDIR"
echo "Check data saved to ${ARCHIVE_PATH}"
exit 0
