#!/bin/sh
# SPDX-License-Identifier: MIT
# ============================================================
# ITCheckAI OS Check Script - VMware ESXi
# Version    : 1.3.0
# Schema     : itcheck.esxi.check/1
# Applies to : ESXi 6.5 / 6.7 / 7.0 / 8.0 (ESXi Shell / SSH, BusyBox ash)
# Usage      : sh vmware-esxi-check-v1.3.0.sh [output-dir] [--cmd-timeout SEC] [--perf-timeout SEC] [--skip-perf]
# Output     : <output-dir>/<hostname>.<serial>.check-<timestamp>.tgz
#              output-dir defaults to the first datastore under /vmfs/volumes/
#              to protect the small /tmp ramdisk, falling back to /tmp only
#              when no datastore is available.
# Note       : Strictly read-only collection; records raw outputs, per-item
#              execution metadata & lightweight check.json manifest.
#              Covers boot device / bootbank / scratch health, syslog config,
#              host SSL certificate expiry (cert metadata only, never private
#              key), maintenance / lockdown / SSH / NTP security posture, vSAN
#              cluster & health (when enabled), VM snapshot inventory (bounded),
#              and hardware RAID controllers & tools (StorCLI / PercCLI /
#              MegaCLI / ARCCONF / SSACLI / SASxIRCU / esxcli SMART).
#              Never reads /etc/shadow, /etc/passwd, /etc/vmware/snmp.xml or
#              private keys; redacts 20 credential classes & RAID Safe ID.
#              For a full official support bundle use `vm-support` instead.
# ============================================================

umask 077

SCRIPT_NAME="vmware-esxi-check"
SCRIPT_VERSION="1.3.0"
SCRIPT_FILE="vmware-esxi-check-v1.3.0.sh"
SCHEMA_VERSION="itcheck.esxi.check/1"

# Stable C locale without altering host TZ
LC_ALL=C
LANG=C
export LC_ALL LANG

OUT_DIR="${ITCHECK_OUT_DIR:-}"
VOLUMES_DIR="${ITCHECK_VOLUMES_DIR:-/vmfs/volumes}"
CMD_TIMEOUT_SEC="${ITCHECK_CMD_TIMEOUT:-30}"
PERF_TIMEOUT_SEC="${ITCHECK_PERF_TIMEOUT:-60}"
MAX_ITEM_BYTES="${ITCHECK_MAX_ITEM_BYTES:-1048576}"
MAX_SNAPSHOT_VMS="${ITCHECK_MAX_SNAPSHOT_VMS:-200}"
SNAPSHOT_TOTAL_TIMEOUT="${ITCHECK_SNAPSHOT_TIMEOUT:-90}"
SKIP_PERF="${ITCHECK_SKIP_PERF:-0}"
ROOT_PREFIX="${ITCHECK_ROOT:-}"

usage() {
    cat <<EOF
Usage: $SCRIPT_FILE [OUTPUT_DIR] [OPTIONS]

Read-only VMware ESXi check collector (schema: $SCHEMA_VERSION).

Options:
  [OUTPUT_DIR], --out-dir DIR  Output directory for .tgz archive (default: first
                               datastore under /vmfs/volumes/, fallback /tmp)
  --cmd-timeout SEC            Per-command timeout in seconds (default: $CMD_TIMEOUT_SEC)
  --perf-timeout SEC           Performance command timeout in seconds (default: $PERF_TIMEOUT_SEC)
  --max-item-bytes N           Max bytes retained per collected item (default: $MAX_ITEM_BYTES)
  --skip-perf                  Skip live esxtop sampling (marks item as skipped)
  --version                    Print script version and 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 ;;
        *)
            if [ -z "$OUT_DIR" ]; then
                OUT_DIR="$1"; shift
            else
                echo "ERROR: unexpected argument: $1" >&2
                usage >&2
                exit 2
            fi ;;
    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; }
is_pos_int "$MAX_SNAPSHOT_VMS" || MAX_SNAPSHOT_VMS=200
is_pos_int "$SNAPSHOT_TOTAL_TIMEOUT" || SNAPSHOT_TOTAL_TIMEOUT=90

# Capture script absolute path before any directory change
SCRIPT_SELF_PATH=""
case "$0" in
    /*) [ -f "$0" ] && SCRIPT_SELF_PATH="$0" ;;
    */*)
        _opwd=$(pwd 2>/dev/null)
        [ -n "$_opwd" ] && [ -f "$_opwd/$0" ] && SCRIPT_SELF_PATH="$_opwd/$0" ;;
esac

# Prefer a datastore for output: /tmp on ESXi is a small ramdisk.
TMP_FALLBACK_WARN=""
if [ -z "$OUT_DIR" ]; then
    for _ds in "${VOLUMES_DIR%/}"/*/; do
        if [ -d "$_ds" ]; then
            OUT_DIR="${_ds%/}"
            break
        fi
    done
    if [ -z "$OUT_DIR" ]; then
        OUT_DIR="/tmp"
        TMP_FALLBACK_WARN="no datastore found under ${VOLUMES_DIR}; falling back to /tmp ramdisk"
    fi
fi

mkdir -p "$OUT_DIR" 2>/dev/null || { echo "ERROR: cannot create $OUT_DIR" >&2; exit 1; }
BASEDIR=$(cd "$OUT_DIR" 2>/dev/null && pwd) || { echo "ERROR: cannot access $OUT_DIR" >&2; exit 1; }

# ── Helpers (strictly BusyBox ash + POSIX awk compatible) ──

iso_now_raw() {
    _inr_dt=$(date '+%Y-%m-%dT%H:%M:%S' 2>/dev/null)
    _inr_off=$(date '+%z' 2>/dev/null)
    case "$_inr_off" in
        [+-][0-9][0-9][0-9][0-9])
            printf '%s%s:%s' "$_inr_dt" "${_inr_off%??}" "${_inr_off#???}"
            return 0 ;;
    esac
    _inr_tz=$(date '+%Z' 2>/dev/null)
    if [ -n "$_inr_tz" ]; then
        printf '%s %s' "$_inr_dt" "$_inr_tz"
    else
        printf '%s' "$_inr_dt"
    fi
}

tz_raw_str() {
    _tz_n=$(date '+%Z' 2>/dev/null)
    _tz_o=$(date '+%z' 2>/dev/null)
    case "$_tz_o" in
        [+-][0-9][0-9][0-9][0-9]) ;;
        *) _tz_o="" ;;
    esac
    if [ -n "$_tz_n" ] && [ -n "$_tz_o" ]; then
        printf '%s %s' "$_tz_n" "$_tz_o"
    elif [ -n "$_tz_n" ]; then
        printf '%s' "$_tz_n"
    else
        printf '%s' "$_tz_o"
    fi
}

now_epoch() {
    _ne=$(date '+%s' 2>/dev/null)
    case "$_ne" in
        ''|*[!0-9]*) printf '0' ;;
        *) printf '%s' "$_ne" ;;
    esac
}

calc_sha256() {
    _cs_f="$1"
    [ -r "$_cs_f" ] || { printf ''; return 0; }
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$_cs_f" 2>/dev/null | awk '{print tolower($1)}'
    elif command -v openssl >/dev/null 2>&1; then
        openssl dgst -sha256 "$_cs_f" 2>/dev/null | awk '{print tolower($NF)}'
    else
        printf ''
    fi
}

file_size_bytes() {
    _fsz=$(wc -c < "$1" 2>/dev/null | tr -d ' \t\r\n')
    case "$_fsz" in
        ''|*[!0-9]*) printf '0' ;;
        *) printf '%s' "$_fsz" ;;
    esac
}

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

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

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"
        n = length($0)
        for (i = 1; i <= n; i++) {
            ch = substr($0, 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 }'
}

# Portable watchdog timeout (works in ESXi BusyBox ash without GNU timeout)
exec_with_timeout() {
    _et_sec="$1"
    _et_out="$2"
    _et_cmd="$3"
    _et_flag="${SCRATCH_DIR}/to.$$"
    rm -f "$_et_flag"
    ( trap - INT TERM HUP; eval "$_et_cmd"; exit $? ) </dev/null >"$_et_out" 2>&1 &
    _et_pid=$!
    (
        trap '' HUP INT
        _reaped_sl=""
        trap 'trap "" TERM
              if [ -n "$_sl" ] && [ "$_sl" != "$_reaped_sl" ]; then
                  kill -TERM "$_sl" 2>/dev/null
                  wait "$_sl" 2>/dev/null
              fi
              exit 0' TERM
        _n=0
        _sl=""
        while [ "$_n" -lt "$_et_sec" ]; do
            sleep 1 &
            _sl=$!
            wait "$_sl" 2>/dev/null
            _reaped_sl="$_sl"
            kill -0 "$_et_pid" 2>/dev/null || exit 0
            _n=$((_n + 1))
        done
        trap '' TERM
        : > "$_et_flag"
        for _cp in $(ps -eo pid,ppid 2>/dev/null | awk -v p="$_et_pid" 'NR>1 && $2==p {print $1}'); do
            kill -TERM "$_cp" 2>/dev/null
        done
        kill -TERM "$_et_pid" 2>/dev/null
        sleep 1
        for _cp in $(ps -eo pid,ppid 2>/dev/null | awk -v p="$_et_pid" 'NR>1 && $2==p {print $1}'); do
            kill -KILL "$_cp" 2>/dev/null
        done
        kill -KILL "$_et_pid" 2>/dev/null
    ) </dev/null >/dev/null 2>&1 &
    _et_wpid=$!
    wait "$_et_pid" 2>/dev/null
    _et_rc=$?
    if [ -f "$_et_flag" ]; then
        wait "$_et_wpid" 2>/dev/null
        rm -f "$_et_flag"
        return 124
    fi
    kill -TERM "$_et_wpid" 2>/dev/null
    wait "$_et_wpid" 2>/dev/null
    rm -f "$_et_flag"
    return "$_et_rc"
}

# Streaming POSIX/BusyBox awk credential redactor (20 classes + ESXi advanced settings Path/String Value)
redact_file() {
    _rf_src="$1"
    _rf_dst="$2"
    _rf_flg="$3"
    awk -v flag_file="$_rf_flg" '
    function is_safe_val(v,   lv) {
        lv = tolower(v)
        return (lv == "" || lv == "<empty>" || lv == "none" || lv == "null" || lv == "true" || lv == "false" || lv == "[redacted]" || lv == "[redacted:hash]" || lv == "[redacted:token]" || lv == "[redacted:jwt]" || lv ~ /^\*+$/)
    }
    function mask_re_len(s, re, min_len, label,   out, rest) {
        out = ""; rest = s
        while (match(rest, re)) {
            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_hashes(s,   out, rest, colon_n, sf, i) {
        if (s ~ /^[A-Za-z0-9_.-]+:[^:!* \t][^: \t]+:[0-9]*:[0-9]*:[0-9]*:/) {
            colon_n = split(s, sf, ":")
            if (colon_n >= 6 && length(sf[2]) >= 8 && !is_safe_val(sf[2])) {
                sf[2] = "[REDACTED:HASH]"
                s = sf[1]
                for (i = 2; i <= colon_n; i++) s = s ":" sf[i]
                changed = 1
            }
        }
        s = mask_re_len(s, "\\$(1|2[aby]|5|6|y|gy|md5|sha256|sha512)\\$[A-Za-z0-9./$+=_-]+", 12, "[REDACTED:HASH]")
        out = ""; rest = s
        while (match(tolower(rest), /\{(ssha256|ssha512|ssha1|smd5|sblowfish|crypt)\}[a-z0-9.\/+=_$-]+/)) {
            if (RLENGTH >= 12) {
                out = out substr(rest, 1, RSTART - 1) "[REDACTED:HASH]"
                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_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, /^[^ \t"'\'';,<>\/]+@/)) {
                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_val(pass_part)) {
                        out = out user_part ":[REDACTED]@"
                        rest = substr(rest, RLENGTH + 1)
                        changed = 1
                        continue
                    }
                }
            }
        }
        return out rest
    }
    function mask_headers_tokens(s,   low, out, rest, head, tail, tok, lead) {
        low = tolower(s)
        if (match(low, /(proxy-)?authorization[ \t]*:[ \t]*(bearer|basic|token|digest|aws4-hmac-sha256)[ \t]+/)) {
            head = substr(s, 1, RSTART + RLENGTH - 1)
            tail = substr(s, RSTART + RLENGTH)
            if (match(tail, /^[^ \t"'\'';,}]+/)) {
                if (!is_safe_val(substr(tail, 1, RLENGTH))) {
                    s = head "[REDACTED]" substr(tail, RLENGTH + 1)
                    changed = 1
                }
            }
        }
        low = tolower(s)
        if (match(low, /(^|[^a-z0-9_-])(set-cookie|cookie|x-auth-token|x-api-key|x-api-token|x-access-token)[ \t]*:[ \t]*/)) {
            head = substr(s, 1, RSTART + RLENGTH - 1)
            tail = substr(s, RSTART + RLENGTH)
            if (!is_safe_val(tail)) {
                s = head "[REDACTED]"
                changed = 1
            }
        }
        out = ""; rest = s
        while (match(tolower(rest), /(^|[^a-z0-9_])bearer[ \t]+/)) {
            head = substr(rest, 1, RSTART + RLENGTH - 1)
            tail = substr(rest, RSTART + RLENGTH)
            if (match(tail, /^[A-Za-z0-9._~+\/=-]+/) && RLENGTH >= 6) {
                if (!is_safe_val(substr(tail, 1, RLENGTH))) {
                    out = out head "[REDACTED]"
                    rest = substr(tail, RLENGTH + 1)
                    changed = 1
                    continue
                }
            }
            out = out head; rest = tail
        }
        s = out rest
        s = mask_re_len(s, "eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+", 24, "[REDACTED:JWT]")
        s = mask_re_len(s, "(AKIA|ASIA)[0-9A-Z]+", 20, "[REDACTED:TOKEN]")
        s = mask_re_len(s, "gh[pousr]_[A-Za-z0-9_]+", 20, "[REDACTED:TOKEN]")
        s = mask_re_len(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_snmp_sql(s,   out, rest, head, tail, val, qch, qpos, low) {
        out = ""; rest = s
        while (match(tolower(rest), /<(communities|community|authkey|privkey|password|secret)>/)) {
            head = substr(rest, 1, RSTART + RLENGTH - 1)
            tail = substr(rest, RSTART + RLENGTH)
            if (match(tail, /^[^<]+</)) {
                val = substr(tail, 1, RLENGTH - 1)
                if (!is_safe_val(val)) {
                    out = out head "[REDACTED]<"
                    rest = substr(tail, RLENGTH + 1)
                    changed = 1
                    continue
                }
            }
            out = out head; rest = tail
        }
        s = out rest
        low = tolower(s)
        if (match(low, /^[ \t]*(rocommunity6?|rwcommunity6?|community|trapsink|trap2sink|informsink)[ \t]+/)) {
            head = substr(s, 1, RSTART + RLENGTH - 1)
            tail = substr(s, RSTART + RLENGTH)
            if (match(tail, /^[^ \t"'\'';,#]+/)) {
                val = substr(tail, 1, RLENGTH)
                if (!is_safe_val(val)) {
                    s = head "[REDACTED]" substr(tail, RLENGTH + 1)
                    changed = 1
                }
            }
        }
        out = ""; rest = s
        while (match(tolower(rest), /(^|[^a-z0-9_])identified[ \t]+by([ \t]+values)?[ \t]+/)) {
            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)
                qpos = index(substr(tail, 2), qch)
                if (qpos > 0) {
                    val = substr(tail, 2, qpos - 1)
                    if (!is_safe_val(val)) {
                        out = out head qch "[REDACTED]" qch
                        rest = substr(tail, 2 + qpos)
                        changed = 1
                        continue
                    }
                }
            } else if (match(tail, /^[^ \t"'\'';,)]+/)) {
                val = substr(tail, 1, RLENGTH)
                if (!is_safe_val(val) && tolower(val) !~ /^(externally|globally|password)$/) {
                    out = out head "[REDACTED]"
                    rest = substr(tail, RLENGTH + 1)
                    changed = 1
                    continue
                }
            }
            out = out head; rest = tail
        }
        return out rest
    }
    function mask_cli_flags(s,   out, rest, head, tail, val, qch, qpos, low, tok, flg, m_start, m_len, after_tok) {
        out = ""; rest = s
        while (match(tolower(rest), /(^|[ \t])--?(password|passwd|pass|pwd|secret|token|api[-_]?key|access[-_]?key|auth[-_]?token|private[-_]?key|client[-_]?secret|passphrase|snmp[-_]?community|community|authpass|privpass|authkey|privkey)(=|[ \t]+)/)) {
            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)
                qpos = index(substr(tail, 2), qch)
                if (qpos > 0) {
                    val = substr(tail, 2, qpos - 1)
                    if (!is_safe_val(val)) {
                        out = out head qch "[REDACTED]" qch
                        rest = substr(tail, 2 + qpos)
                        changed = 1
                        continue
                    }
                }
            } else if (match(tail, /^[^ \t"'\'';,)}]+/)) {
                val = substr(tail, 1, RLENGTH)
                if (!is_safe_val(val)) {
                    out = out head "[REDACTED]"
                    rest = substr(tail, RLENGTH + 1)
                    changed = 1
                    continue
                }
            }
            out = out head; rest = tail
        }
        s = out rest
        low = tolower(s)
        if (low ~ /(mysql|mysqldump|mysqladmin|sshpass|redis-cli|ipmitool|curl|wget|sqlcmd|snmpwalk|snmpget|snmptrap|snmpbulkwalk|ldapsearch|smbclient)/) {
            out = ""; rest = s
            while (match(rest, /(^|[ \t])(-p|-P|-a|-u|--user|-c|-w|-A|-X)([ \t]+|[^ \t"'\'';,]+)/)) {
                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, /^[ \t]*(-p|-P|-a|-u|--user|-c|-w|-A|-X)[ \t]+/)) {
                    flg = substr(tok, 1, RLENGTH)
                    if (match(after_tok, /^[^ \t"'\'';,]+/)) {
                        val = substr(after_tok, 1, RLENGTH)
                        if (!is_safe_val(val) && substr(val, 1, 1) != "-") {
                            out = out head flg "[REDACTED]"
                            rest = substr(after_tok, RLENGTH + 1)
                            changed = 1
                            continue
                        }
                    }
                } else if (match(tok, /^[ \t]*(-p|-P|-a|-c|-w|-A|-X)/)) {
                    flg = substr(tok, 1, RLENGTH)
                    val = substr(tok, RLENGTH + 1)
                    if (!is_safe_val(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(s,   out, rest, head, tail, val, qch, qpos) {
        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|community_string|rocommunity|rwcommunity|chap_password|password_in|incoming_password|initiator_secret|mutual_secret|mysql_pwd|pgpassword|sqlcmdpassword|dm_pass|oracle_pwd|aws_secret_access_key|accountkey|sharedaccesskey|luks\.key|luks_key|credentials_password|credential|authpass|privpass|authkey|privkey)["'\'']*[ \t]*(=|:)[ \t]*/)) {
            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)
                qpos = index(substr(tail, 2), qch)
                if (qpos > 0) {
                    val = substr(tail, 2, qpos - 1)
                    if (!is_safe_val(val)) {
                        out = out head qch "[REDACTED]" qch
                        rest = substr(tail, 2 + qpos)
                        changed = 1
                        continue
                    }
                }
            } else if (match(tail, /^[^ \t"'\'';,)}]+/)) {
                val = substr(tail, 1, RLENGTH)
                if (!is_safe_val(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; adv_sens = 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
        }
        low_l = tolower(line)
        # Track ESXi advanced settings multi-line stanza: Path: /.../Password -> String Value: ...
        if (low_l ~ /^[ \t]*path[ \t]*:/) {
            adv_sens = (low_l ~ /(password|passwd|secret|token|community|apikey|api_key|passphrase|private_key|authkey|privkey|credential)/) ? 1 : 0
        } else if (adv_sens == 1 && match(low_l, /^[ \t]*(default[ \t]+)?string value[ \t]*:[ \t]*/)) {
            _h = substr(line, 1, RSTART + RLENGTH - 1)
            _t = substr(line, RSTART + RLENGTH)
            if (!is_safe_val(_t)) {
                line = _h "[REDACTED]"
                changed = 1
                print line
                next
            }
        }
        if (match(low_l, /^[ \t]*safe[ \t]+id[ \t]*=[ \t]*/)) {
            _sv = substr(line, RSTART + RLENGTH)
            sub(/[ \t]+$/, "", _sv)
            if (!is_safe_val(_sv)) {
                line = substr(line, 1, RSTART + RLENGTH - 1) "[REDACTED]"
                changed = 1
                print line
                next
            }
        }
        if (low_l ~ /(pass|pwd|secret|token|key|auth|cookie|bearer|eyj|akia|asia|gh[pousr]_|glpat-|sk-|xox|communit|trap|identif|cred|chap|luks|ssha|smd5|sblowfish|\$(1|2|5|6|y|gy|md5|sha)|:\/\/|mysql|sshpass|redis-cli|ipmitool|curl|wget|sqlcmd|snmp|ldap|smbclient|^[a-z0-9_.-]+:[^:!* \t][^: \t]+:[0-9]*:[0-9]*:[0-9]*:)/) {
            line = mask_hashes(line)
            line = mask_urls(line)
            line = mask_headers_tokens(line)
            line = mask_snmp_sql(line)
            line = mask_cli_flags(line)
            line = mask_kv(line)
        }
        print line
    }
    END { printf "%d\n", changed > flag_file }' "$_rf_src" > "$_rf_dst"
}

is_perm_err_file() {
    grep -iE 'permission denied|operation not permitted|must be root|not superuser|not authorized|insufficient permission|access denied|requires root|no permission' "$1" >/dev/null 2>&1
}

# ── Host Identity & Start Metadata ──

START_ISO=$(iso_now_raw)
START_EPOCH=$(now_epoch)
DATE_RAW=$(date 2>/dev/null || printf '%s' "$START_ISO")
TZ_RAW=$(tz_raw_str)
STAMP=$(date '+%Y%m%d_%H%M%S' 2>/dev/null || echo "19700101_000000")

RUN_AS_UID=$(id -u 2>/dev/null)
case "$RUN_AS_UID" in ''|*[!0-9]*) RUN_AS_UID=65534 ;; esac
RUN_AS_USER=$(id -un 2>/dev/null)
[ -z "$RUN_AS_USER" ] && RUN_AS_USER="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 esxcli >/dev/null 2>&1; then
    SERIAL_RAW=$(esxcli hardware platform get 2>/dev/null | awk -F': ' '/Serial Number/{print $2; exit}' | tr -d ' /')
    [ -n "$SERIAL_RAW" ] && SERIAL_SOURCE="esxcli"
fi
SERIAL_FOR_NAME="$SERIAL_RAW"
[ -z "$SERIAL_FOR_NAME" ] && SERIAL_FOR_NAME="NotAvailable"
SERIAL_FOR_NAME=$(sanitize_token "$SERIAL_FOR_NAME")

OS_VERSION_STR=$(vmware -vl 2>/dev/null | head -n 1)
ARCH_STR=$(uname -m 2>/dev/null)
SCRIPT_SELF_SHA256=""
[ -n "$SCRIPT_SELF_PATH" ] && SCRIPT_SELF_SHA256=$(calc_sha256 "$SCRIPT_SELF_PATH")

DIRNAME="${HOSTNAME_SAFE}.${SERIAL_FOR_NAME}.check-${STAMP}"
CFGDIR="${BASEDIR%/}/${DIRNAME}"
mkdir -p "$CFGDIR" || { echo "ERROR: cannot create $CFGDIR" >&2; exit 1; }

SCRATCH_DIR="${BASEDIR%/}/.itcheck_esxi_tmp_$$"
_sc_try=0
while ! mkdir -m 700 "$SCRATCH_DIR" 2>/dev/null; do
    _sc_try=$((_sc_try + 1))
    [ "$_sc_try" -ge 10 ] && { echo "ERROR: cannot create scratch dir" >&2; exit 1; }
    SCRATCH_DIR="${BASEDIR%/}/.itcheck_esxi_tmp_$$_${_sc_try}"
done
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
}
trap cleanup_scratch EXIT
trap 'cleanup_scratch; exit 130' HUP INT TERM

printf '%s\n' "$DATE_RAW" > "$CFGDIR/date.log"

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

if [ -n "$TMP_FALLBACK_WARN" ]; then
    echo "WARNING: $TMP_FALLBACK_WARN" >&2
    add_warning "$TMP_FALLBACK_WARN"
fi
if [ "$IS_ROOT" != "true" ]; then
    NON_ROOT_WARN="WARNING: not running as root (uid=${RUN_AS_UID}), some esxcli hardware/storage/log data will be incomplete."
    printf '%s\n' "$NON_ROOT_WARN" | tee "$CFGDIR/warning.txt"
    add_warning "$NON_ROOT_WARN"
fi

# Item status counters
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; CNT_REDACTED=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
}

classify_status() {
    _cs_rc="$1"; _cs_req="$2"; _cs_out="$3"
    if [ "$_cs_rc" -eq 124 ]; then
        echo "timeout"; return 0
    elif [ "$_cs_rc" -eq 127 ]; then
        echo "command_missing"; return 0
    elif [ "$_cs_rc" -eq 0 ]; then
        if [ "$IS_ROOT" != "true" ] && [ "$_cs_req" = "true" ] && is_perm_err_file "$_cs_out"; then
            if ! grep -viE 'permission denied|operation not permitted|must be root|not superuser|not authorized|insufficient permission|access denied' "$_cs_out" 2>/dev/null | grep -q '[^ 	]'; then
                echo "permission_denied"; return 0
            fi
        fi
        if [ -s "$_cs_out" ] && grep -q '[^ 	]' "$_cs_out" 2>/dev/null; then
            echo "ok"
        else
            echo "empty"
        fi
        return 0
    else
        if [ "$IS_ROOT" != "true" ] && { [ "$_cs_req" = "true" ] || is_perm_err_file "$_cs_out"; }; then
            echo "permission_denied"; return 0
        fi
        if is_perm_err_file "$_cs_out"; then
            echo "permission_denied"; return 0
        fi
        echo "failed"
    fi
}

# finalize_item id section rel_path display_cmd req_root start_iso start_ep rc status t_sec body_file note
finalize_item() {
    _fi_id="$1"; _fi_sec="$2"; _fi_rel="$3"; _fi_cmd="$4"; _fi_req="$5"
    _fi_siso="$6"; _fi_sep="$7"; _fi_rc="$8"; _fi_st="$9"
    shift 9
    _fi_tsec="$1"; _fi_body="$2"; _fi_note="$3"

    _fi_out="${CFGDIR}/${_fi_rel}"
    mkdir -p "$(dirname "$_fi_out")"

    _fi_work="${SCRATCH_DIR}/work.tmp"
    _fi_flg="${SCRATCH_DIR}/red.flag"
    _fi_red="false"
    _fi_trunc="false"
    : > "$_fi_work"
    if [ -s "$_fi_body" ]; then
        redact_file "$_fi_body" "$_fi_work" "$_fi_flg"
        if [ "$(cat "$_fi_flg" 2>/dev/null)" = "1" ]; then
            _fi_red="true"
            CNT_REDACTED=$((CNT_REDACTED + 1))
        fi
    fi

    _fi_bytes=$(file_size_bytes "$_fi_work")
    if [ "$_fi_bytes" -gt "$MAX_ITEM_BYTES" ]; then
        dd if="$_fi_work" of="${SCRATCH_DIR}/trunc.tmp" bs=1 count="$MAX_ITEM_BYTES" 2>/dev/null || \
            head -c "$MAX_ITEM_BYTES" "$_fi_work" > "${SCRATCH_DIR}/trunc.tmp" 2>/dev/null
        printf '\n[output truncated at %s bytes]\n' "$MAX_ITEM_BYTES" >> "${SCRATCH_DIR}/trunc.tmp"
        mv "${SCRATCH_DIR}/trunc.tmp" "$_fi_work"
        _fi_trunc="true"
    fi

    {
        printf '### %s\n' "$_fi_cmd"
        if [ -s "$_fi_work" ]; then
            cat "$_fi_work"
            printf '\n'
        fi
        case "$_fi_st" in
            command_missing)   printf '[command missing: %s]\n' "${_fi_note:-$_fi_cmd}" ;;
            permission_denied) printf '[permission denied: %s]\n' "${_fi_note:-requires root privileges}" ;;
            timeout)           printf '[command timed out after %ss]\n' "$_fi_tsec" ;;
            not_applicable)    printf '[not applicable: %s]\n' "${_fi_note:-resource not present}" ;;
            skipped)           printf '[skipped: %s]\n' "${_fi_note:-skipped by option}" ;;
            failed)            printf '[command failed with exit code %s]\n' "$_fi_rc" ;;
        esac
    } > "$_fi_out"

    _fi_eiso=$(iso_now_raw)
    _fi_eep=$(now_epoch)
    _fi_dur=$((_fi_eep - _fi_sep))
    [ "$_fi_dur" -lt 0 ] && _fi_dur=0

    _fi_fsz=$(file_size_bytes "$_fi_out")
    _fi_sha=$(calc_sha256 "$_fi_out")
    bump_status_count "$_fi_st"

    _j_id=$(printf '%s' "$_fi_id" | json_escape)
    _j_sec=$(printf '%s' "$_fi_sec" | json_escape)
    _j_rel=$(printf '%s' "$_fi_rel" | json_escape)
    _j_cmd=$(printf '%s' "$_fi_cmd" | json_escape)
    _j_siso=$(printf '%s' "$_fi_siso" | json_escape)
    _j_eiso=$(printf '%s' "$_fi_eiso" | json_escape)
    _j_st=$(printf '%s' "$_fi_st" | json_escape)
    _j_sha=$(printf '%s' "$_fi_sha" | json_escape)
    _j_note_f=""
    if [ -n "$_fi_note" ]; then
        _j_note_f=",\"note\":$(printf '%s' "$_fi_note" | json_escape)"
    fi

    printf '{"id":%s,"section":%s,"path":%s,"command":%s,"requires_root":%s,"started_at_raw":%s,"finished_at_raw":%s,"duration_sec":%s,"exit_code":%s,"status":%s,"timeout_sec":%s,"truncated":%s,"redacted":%s,"size_bytes":%s,"sha256":%s%s}\n' \
        "$_j_id" "$_j_sec" "$_j_rel" "$_j_cmd" "$_fi_req" "$_j_siso" "$_j_eiso" "$_fi_dur" \
        "$_fi_rc" "$_j_st" "$_fi_tsec" "$_fi_trunc" "$_fi_red" "$_fi_fsz" "$_j_sha" "$_j_note_f" >> "$ITEMS_JSONL"
}

# run_cmd id section rel_path req_root t_sec post_filter display_cmd primary_bin shell_cmd
run_cmd() {
    _rc_id="$1"; _rc_sec="$2"; _rc_rel="$3"; _rc_req="$4"; _rc_tsec="$5"
    _rc_flt="$6"; _rc_disp="$7"; _rc_bin="$8"; _rc_cmd="$9"

    _rc_siso=$(iso_now_raw)
    _rc_sep=$(now_epoch)
    _rc_raw="${SCRATCH_DIR}/raw.tmp"
    _rc_out="${SCRATCH_DIR}/flt.tmp"
    : > "$_rc_raw"
    : > "$_rc_out"

    if [ -n "$_rc_bin" ] && ! command -v "$_rc_bin" >/dev/null 2>&1; then
        finalize_item "$_rc_id" "$_rc_sec" "$_rc_rel" "$_rc_disp" "$_rc_req" \
            "$_rc_siso" "$_rc_sep" 127 "command_missing" "$_rc_tsec" "$_rc_out" "command not found: $_rc_bin"
        return 0
    fi

    exec_with_timeout "$_rc_tsec" "$_rc_raw" "$_rc_cmd"
    _rc_code=$?
    _rc_st=$(classify_status "$_rc_code" "$_rc_req" "$_rc_raw")
    _rc_note=""
    [ "$_rc_st" = "permission_denied" ] && _rc_note="permission denied (uid=${RUN_AS_UID})"
    [ "$_rc_st" = "timeout" ] && _rc_note="timed out after ${_rc_tsec}s"

    case "$_rc_flt" in
        head:*) head -n "${_rc_flt#head:}" "$_rc_raw" > "$_rc_out" ;;
        tail:*) tail -n "${_rc_flt#tail:}" "$_rc_raw" > "$_rc_out" ;;
        *) cp "$_rc_raw" "$_rc_out" ;;
    esac

    finalize_item "$_rc_id" "$_rc_sec" "$_rc_rel" "$_rc_disp" "$_rc_req" \
        "$_rc_siso" "$_rc_sep" "$_rc_code" "$_rc_st" "$_rc_tsec" "$_rc_out" "$_rc_note"
}

# run_multi id section rel_path req_root t_sec display_cmd "bin1::cmd1" "bin2::cmd2" ...
run_multi() {
    _rm_id="$1"; _rm_sec="$2"; _rm_rel="$3"; _rm_req="$4"; _rm_tsec="$5"; _rm_disp="$6"
    shift 6
    _rm_siso=$(iso_now_raw)
    _rm_sep=$(now_epoch)
    _rm_comb="${SCRATCH_DIR}/comb.tmp"
    _rm_sub="${SCRATCH_DIR}/sub.tmp"
    : > "$_rm_comb"

    _rm_found=0; _rm_ok=0; _rm_nonempty=0; _rm_perm=0; _rm_to=0; _rm_lastrc=127
    for _spec in "$@"; do
        _sb="${_spec%%::*}"
        _sc="${_spec#*::}"
        _slim=""
        case "$_sc" in
            *::head:*) _slim="${_sc##*::head:}"; _sc="${_sc%::head:*}" ;;
        esac
        if [ -n "$_sb" ]; then
            case "$_sb" in
                /*) [ -x "$_sb" ] || continue ;;
                *) command -v "$_sb" >/dev/null 2>&1 || continue ;;
            esac
        fi
        _rm_found=1
        : > "$_rm_sub"
        exec_with_timeout "$_rm_tsec" "$_rm_sub" "$_sc"
        _src=$?
        _rm_lastrc="$_src"
        _sst=$(classify_status "$_src" "$_rm_req" "$_rm_sub")
        {
            printf '## %s\n' "$_sc"
            if [ -n "$_slim" ]; then
                head -n "$_slim" "$_rm_sub"
            else
                cat "$_rm_sub"
            fi
            printf '\n'
        } >> "$_rm_comb"
        case "$_sst" in
            ok) _rm_ok=1; _rm_nonempty=1 ;;
            empty) _rm_ok=1 ;;
            timeout) _rm_to=1 ;;
            permission_denied) _rm_perm=1 ;;
        esac
    done

    _rm_note=""
    if [ "$_rm_found" -eq 0 ]; then
        _rm_st="command_missing"; _rm_lastrc=127; _rm_note="no matching command available"
    elif [ "$_rm_to" -eq 1 ]; then
        _rm_st="timeout"; _rm_lastrc=124; _rm_note="subcommand timed out after ${_rm_tsec}s"
    elif [ "$_rm_ok" -eq 1 ]; then
        [ "$_rm_nonempty" -eq 1 ] && _rm_st="ok" || _rm_st="empty"
        _rm_lastrc=0
    elif [ "$_rm_perm" -eq 1 ]; then
        _rm_st="permission_denied"; _rm_note="requires root privileges (uid=${RUN_AS_UID})"
    else
        _rm_st="failed"
    fi

    finalize_item "$_rm_id" "$_rm_sec" "$_rm_rel" "$_rm_disp" "$_rm_req" \
        "$_rm_siso" "$_rm_sep" "$_rm_lastrc" "$_rm_st" "$_rm_tsec" "$_rm_comb" "$_rm_note"
}

run_log_tail() {
    _rl_id="$1"; _rl_rel="$2"; _rl_path="$3"; _rl_lines="$4"
    _rl_real="${ROOT_PREFIX}${_rl_path}"
    _rl_disp="tail -n ${_rl_lines} ${_rl_path}"
    _rl_siso=$(iso_now_raw)
    _rl_sep=$(now_epoch)
    _rl_raw="${SCRATCH_DIR}/log.tmp"
    : > "$_rl_raw"

    if [ ! -e "$_rl_real" ]; then
        finalize_item "$_rl_id" "logs" "$_rl_rel" "$_rl_disp" "true" \
            "$_rl_siso" "$_rl_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_rl_raw" "file not present: $_rl_path"
        return 0
    fi
    if [ ! -r "$_rl_real" ]; then
        finalize_item "$_rl_id" "logs" "$_rl_rel" "$_rl_disp" "true" \
            "$_rl_siso" "$_rl_sep" 1 "permission_denied" "$CMD_TIMEOUT_SEC" "$_rl_raw" "cannot read $_rl_path (uid=${RUN_AS_UID})"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_rl_raw" "tail -n ${_rl_lines} \"${_rl_real}\""
    _rl_rc=$?
    _rl_st=$(classify_status "$_rl_rc" "true" "$_rl_raw")
    _rl_note=""
    [ "$_rl_st" = "timeout" ] && _rl_note="timed out after ${CMD_TIMEOUT_SEC}s"
    finalize_item "$_rl_id" "logs" "$_rl_rel" "$_rl_disp" "true" \
        "$_rl_siso" "$_rl_sep" "$_rl_rc" "$_rl_st" "$CMD_TIMEOUT_SEC" "$_rl_raw" "$_rl_note"
}

# Read-only boot device, bootbank & scratch health inspection (no raw dd reads).
# Identifies SD/USB boot media and ramdisk scratch risks.
collect_boot_health() {
    _bh_siso=$(iso_now_raw); _bh_sep=$(now_epoch)
    _bh_comb="${SCRATCH_DIR}/boot_health.tmp"
    _bh_sub="${SCRATCH_DIR}/boot_sub.tmp"
    _bh_devs="${SCRATCH_DIR}/boot_devs.tmp"
    _bh_scr="${SCRATCH_DIR}/boot_scr.tmp"
    : > "$_bh_comb"; : > "$_bh_devs"; : > "$_bh_scr"

    _bh_ok=0; _bh_to=0; _bh_perm=0; _bh_found=0

    if command -v esxcli >/dev/null 2>&1; then
        _bh_found=1
        : > "$_bh_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bh_sub" "esxcli system boot device get"
        _rc=$?
        [ "$_rc" -eq 0 ] && _bh_ok=1
        [ "$_rc" -eq 124 ] && _bh_to=1
        is_perm_err_file "$_bh_sub" && _bh_perm=1
        printf '## esxcli system boot device get\n' >> "$_bh_comb"
        cat "$_bh_sub" >> "$_bh_comb"
        printf '\n' >> "$_bh_comb"

        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bh_devs" "esxcli storage core device list"
        _drc=$?
        [ "$_drc" -eq 0 ] && _bh_ok=1
        [ "$_drc" -eq 124 ] && _bh_to=1

        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bh_scr" "esxcli system settings advanced list -o /ScratchConfig/CurrentScratchLocation"
        _src=$?
        [ "$_src" -eq 0 ] && _bh_ok=1
        [ "$_src" -eq 124 ] && _bh_to=1
        printf '## esxcli system settings advanced list -o /ScratchConfig/CurrentScratchLocation\n' >> "$_bh_comb"
        cat "$_bh_scr" >> "$_bh_comb"
        printf '\n' >> "$_bh_comb"

        : > "$_bh_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bh_sub" "esxcli system settings advanced list -o /ScratchConfig/ConfiguredScratchLocation"
        printf '## esxcli system settings advanced list -o /ScratchConfig/ConfiguredScratchLocation\n' >> "$_bh_comb"
        cat "$_bh_sub" >> "$_bh_comb"
        printf '\n' >> "$_bh_comb"
    fi

    if command -v vmkfstools >/dev/null 2>&1; then
        _bh_found=1
        : > "$_bh_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bh_sub" "vmkfstools -P \"${ROOT_PREFIX}/bootbank\""
        _vrc=$?
        [ "$_vrc" -eq 0 ] && _bh_ok=1
        [ "$_vrc" -eq 124 ] && _bh_to=1
        printf '## vmkfstools -P /bootbank\n' >> "$_bh_comb"
        cat "$_bh_sub" >> "$_bh_comb"
        printf '\n' >> "$_bh_comb"
    fi

    if command -v stat >/dev/null 2>&1; then
        _bh_found=1
        printf '## stat -f /bootbank /altbootbank\n' >> "$_bh_comb"
        for _bp in /bootbank /altbootbank; do
            _real_bp="${ROOT_PREFIX}${_bp}"
            if [ -e "$_real_bp" ]; then
                : > "$_bh_sub"
                exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bh_sub" "stat -f \"${_real_bp}\""
                _brc=$?
                [ "$_brc" -eq 0 ] && _bh_ok=1
                [ "$_brc" -eq 124 ] && _bh_to=1
                printf '# %s\n' "$_bp" >> "$_bh_comb"
                cat "$_bh_sub" >> "$_bh_comb"
                printf '\n' >> "$_bh_comb"
            else
                printf '# %s: not present\n' "$_bp" >> "$_bh_comb"
            fi
        done
    fi

    if [ -e "${ROOT_PREFIX}/scratch" ] || [ -L "${ROOT_PREFIX}/scratch" ]; then
        printf '## ls -ld /scratch\n' >> "$_bh_comb"
        ls -ld "${ROOT_PREFIX}/scratch" >> "$_bh_comb" 2>&1
        printf '\n' >> "$_bh_comb"
    fi

    # Synthesize read-only boot media & scratch ramdisk risk summary
    _scr_loc=$(awk -F': *' '/^[ \t]*String Value:/ {print $2; exit}' "$_bh_scr" 2>/dev/null | sed 's/^[ \t]*//; s/[ \t]*$//')
    if [ -z "$_scr_loc" ] && [ -L "${ROOT_PREFIX}/scratch" ]; then
        _scr_loc=$(ls -ld "${ROOT_PREFIX}/scratch" 2>/dev/null | awk -F'-> ' 'NF>1 {print $2}')
    fi
    _scr_ram="unknown"
    case "$_scr_loc" in
        /tmp/*|/tmp) _scr_ram="true" ;;
        /vmfs/volumes/*) _scr_ram="false" ;;
    esac
    {
        printf '## boot_device_summary\n'
        if [ -s "$_bh_devs" ]; then
            awk '
            function flush_dev() {
                if (dev != "" && is_boot == "true") {
                    found = 1
                    printf "boot_device=%s\n", dev
                    printf "boot_vendor=%s\n", (vendor != "" ? vendor : "unknown")
                    printf "boot_model=%s\n", (model != "" ? model : "unknown")
                    printf "boot_size_mb=%s\n", (size != "" ? size : "unknown")
                    printf "boot_is_local=%s\n", (is_local != "" ? is_local : "unknown")
                    printf "boot_is_usb=%s\n", (is_usb != "" ? is_usb : "unknown")
                    printf "boot_is_ssd=%s\n", (is_ssd != "" ? is_ssd : "unknown")
                    printf "boot_is_sas=%s\n", (is_sas != "" ? is_sas : "unknown")
                    printf "boot_status=%s\n", (status != "" ? status : "unknown")
                }
                dev=""; vendor=""; model=""; size=""; is_boot=""; is_local=""; is_usb=""; is_ssd=""; is_sas=""; status=""
            }
            /^[^ \t]/ { flush_dev(); dev=$1; next }
            /^[ \t]+Vendor:/         { sub(/^[^:]+:[ \t]*/, ""); vendor=$0; next }
            /^[ \t]+Model:/          { sub(/^[^:]+:[ \t]*/, ""); model=$0; next }
            /^[ \t]+Size:/           { sub(/^[^:]+:[ \t]*/, ""); size=$0; next }
            /^[ \t]+Is Boot Device:/ { sub(/^[^:]+:[ \t]*/, ""); is_boot=tolower($1); next }
            /^[ \t]+Is Local:/       { sub(/^[^:]+:[ \t]*/, ""); is_local=tolower($1); next }
            /^[ \t]+Is USB:/         { sub(/^[^:]+:[ \t]*/, ""); is_usb=tolower($1); next }
            /^[ \t]+Is SSD:/         { sub(/^[^:]+:[ \t]*/, ""); is_ssd=tolower($1); next }
            /^[ \t]+Is SAS:/         { sub(/^[^:]+:[ \t]*/, ""); is_sas=tolower($1); next }
            /^[ \t]+Status:/         { sub(/^[^:]+:[ \t]*/, ""); status=$0; next }
            END {
                flush_dev()
                if (!found) printf "boot_device=not_identified_in_device_list\n"
            }' "$_bh_devs" 2>/dev/null
        else
            printf 'boot_device=unavailable\n'
        fi
        printf 'scratch_location=%s\n' "${_scr_loc:-unknown}"
        printf 'scratch_on_ramdisk=%s\n' "$_scr_ram"
    } >> "$_bh_comb"

    _bh_note=""
    if [ "$_bh_found" -eq 0 ]; then
        _bh_st="command_missing"; _bh_rc=127; _bh_note="esxcli, vmkfstools and stat not found"
    elif [ "$_bh_to" -eq 1 ]; then
        _bh_st="timeout"; _bh_rc=124; _bh_note="subcommand timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$_bh_ok" -eq 1 ]; then
        _bh_st="ok"; _bh_rc=0
    elif [ "$_bh_perm" -eq 1 ]; then
        _bh_st="permission_denied"; _bh_rc=1; _bh_note="permission denied (uid=${RUN_AS_UID})"
    else
        _bh_st="ok"; _bh_rc=0
    fi
    finalize_item "system.boot_health" "system" "system/boot-health.log" \
        "esxcli system boot device get; vmkfstools -P /bootbank; stat -f /bootbank /altbootbank; scratch & boot media summary" \
        "false" "$_bh_siso" "$_bh_sep" "$_bh_rc" "$_bh_st" "$CMD_TIMEOUT_SEC" "$_bh_comb" "$_bh_note"
}

# Read-only host SSL certificate metadata check (strictly public cert only; never touches private key).
collect_ssl_cert() {
    _sc_siso=$(iso_now_raw); _sc_sep=$(now_epoch)
    _sc_raw="${SCRATCH_DIR}/ssl_cert.tmp"
    : > "$_sc_raw"
    _sc_path="${ROOT_PREFIX}/etc/vmware/ssl/rui.crt"
    _sc_disp="openssl x509 -noout -subject -issuer -dates -in /etc/vmware/ssl/rui.crt"

    if ! command -v openssl >/dev/null 2>&1; then
        finalize_item "system.ssl_cert" "system" "system/ssl-cert.log" "$_sc_disp" "false" \
            "$_sc_siso" "$_sc_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_sc_raw" "command not found: openssl"
        return 0
    fi
    if [ ! -e "$_sc_path" ]; then
        finalize_item "system.ssl_cert" "system" "system/ssl-cert.log" "$_sc_disp" "false" \
            "$_sc_siso" "$_sc_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_sc_raw" "file not present: /etc/vmware/ssl/rui.crt"
        return 0
    fi
    if [ ! -r "$_sc_path" ]; then
        finalize_item "system.ssl_cert" "system" "system/ssl-cert.log" "$_sc_disp" "false" \
            "$_sc_siso" "$_sc_sep" 1 "permission_denied" "$CMD_TIMEOUT_SEC" "$_sc_raw" "cannot read /etc/vmware/ssl/rui.crt (uid=${RUN_AS_UID})"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_sc_raw" "openssl x509 -noout -subject -issuer -dates -serial -in \"${_sc_path}\""
    _sc_rc=$?
    if [ "$_sc_rc" -ne 0 ] && [ "$_sc_rc" -ne 124 ]; then
        : > "$_sc_raw"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_sc_raw" "openssl x509 -noout -subject -issuer -dates -in \"${_sc_path}\""
        _sc_rc=$?
    fi
    _sc_st=$(classify_status "$_sc_rc" "false" "$_sc_raw")
    _sc_note=""
    [ "$_sc_st" = "permission_denied" ] && _sc_note="permission denied (uid=${RUN_AS_UID})"
    [ "$_sc_st" = "timeout" ] && _sc_note="timed out after ${CMD_TIMEOUT_SEC}s"
    finalize_item "system.ssl_cert" "system" "system/ssl-cert.log" "$_sc_disp" "false" \
        "$_sc_siso" "$_sc_sep" "$_sc_rc" "$_sc_st" "$CMD_TIMEOUT_SEC" "$_sc_raw" "$_sc_note"
}

# Read-only maintenance/lockdown mode summary & SSH/Shell/NTP service baseline.
collect_security_mode() {
    _sm_siso=$(iso_now_raw); _sm_sep=$(now_epoch)
    _sm_comb="${SCRATCH_DIR}/sec_mode.tmp"
    _sm_sub="${SCRATCH_DIR}/sec_sub.tmp"
    : > "$_sm_comb"

    _sm_found=0; _sm_ok=0; _sm_to=0; _sm_perm=0; _sm_lrc=127

    if command -v vim-cmd >/dev/null 2>&1; then
        _sm_found=1
        : > "$_sm_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_sm_sub" "vim-cmd hostsvc/hostsummary"
        _vrc=$?; _sm_lrc="$_vrc"
        _vst=$(classify_status "$_vrc" "true" "$_sm_sub")
        printf '## vim-cmd hostsvc/hostsummary (key security & runtime fields)\n' >> "$_sm_comb"
        if [ "$_vst" = "ok" ]; then
            _sm_ok=1
            _sm_flt="${SCRATCH_DIR}/sec_hs_flt.tmp"
            awk '/inMaintenanceMode|lockdownMode|inQuarantineMode|overallStatus|connectionState|powerState|rebootRequired|standbyMode|cryptoState/ {
                gsub(/^[ \t]+/, "")
                print
            }' "$_sm_sub" > "$_sm_flt" 2>/dev/null
            if [ -s "$_sm_flt" ]; then
                cat "$_sm_flt" >> "$_sm_comb"
            else
                head -n 40 "$_sm_sub" >> "$_sm_comb"
            fi
        else
            cat "$_sm_sub" >> "$_sm_comb"
            [ "$_vst" = "timeout" ] && _sm_to=1
            [ "$_vst" = "permission_denied" ] && _sm_perm=1
        fi
        printf '\n' >> "$_sm_comb"
    fi

    if command -v chkconfig >/dev/null 2>&1; then
        _sm_found=1
        for _svc in ntpd SSH ESXiShell; do
            : > "$_sm_sub"
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$_sm_sub" "chkconfig --list ${_svc}"
            _crc=$?; _sm_lrc="$_crc"
            _cst=$(classify_status "$_crc" "false" "$_sm_sub")
            printf '## chkconfig --list %s\n' "$_svc" >> "$_sm_comb"
            cat "$_sm_sub" >> "$_sm_comb"
            printf '\n' >> "$_sm_comb"
            case "$_cst" in
                ok|empty) _sm_ok=1 ;;
                timeout) _sm_to=1 ;;
                permission_denied) _sm_perm=1 ;;
            esac
        done
    fi

    for _init_svc in ntpd SSH ESXiShell; do
        if [ -x "${ROOT_PREFIX}/etc/init.d/${_init_svc}" ]; then
            _sm_found=1
            : > "$_sm_sub"
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$_sm_sub" "\"${ROOT_PREFIX}/etc/init.d/${_init_svc}\" status"
            _nrc=$?
            [ "$_nrc" -eq 0 ] && _sm_ok=1
            [ "$_nrc" -eq 124 ] && _sm_to=1
            printf '## /etc/init.d/%s status\n' "$_init_svc" >> "$_sm_comb"
            cat "$_sm_sub" >> "$_sm_comb"
            printf '\n' >> "$_sm_comb"
        fi
    done

    _sm_note=""
    if [ "$_sm_found" -eq 0 ]; then
        _sm_st="command_missing"; _sm_lrc=127; _sm_note="vim-cmd and chkconfig not found"
    elif [ "$_sm_to" -eq 1 ]; then
        _sm_st="timeout"; _sm_lrc=124; _sm_note="subcommand timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$_sm_ok" -eq 1 ]; then
        _sm_st="ok"; _sm_lrc=0
    elif [ "$_sm_perm" -eq 1 ]; then
        _sm_st="permission_denied"; _sm_note="requires root privileges (uid=${RUN_AS_UID})"
    else
        _sm_st="failed"
    fi
    finalize_item "system.security_mode" "system" "system/security-mode.log" \
        "vim-cmd hostsvc/hostsummary (maintenance/lockdown summary); chkconfig --list ntpd / SSH / ESXiShell" \
        "true" "$_sm_siso" "$_sm_sep" "$_sm_lrc" "$_sm_st" "$CMD_TIMEOUT_SEC" "$_sm_comb" "$_sm_note"
}

# Read-only vSAN cluster & health check (marks not_applicable when vSAN is disabled).
collect_vsan_health() {
    _vs_siso=$(iso_now_raw); _vs_sep=$(now_epoch)
    _vs_comb="${SCRATCH_DIR}/vsan_comb.tmp"
    _vs_cl="${SCRATCH_DIR}/vsan_cl.tmp"
    _vs_hl="${SCRATCH_DIR}/vsan_hl.tmp"
    : > "$_vs_comb"; : > "$_vs_cl"; : > "$_vs_hl"
    _vs_disp="esxcli vsan cluster get; esxcli vsan health cluster list"

    if ! command -v esxcli >/dev/null 2>&1; then
        finalize_item "storage.vsan" "storage" "storage/vsan.log" "$_vs_disp" "true" \
            "$_vs_siso" "$_vs_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_vs_comb" "command not found: esxcli"
        return 0
    fi

    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_vs_cl" "esxcli vsan cluster get"
    _vs_rc=$?
    if [ "$_vs_rc" -eq 124 ]; then
        finalize_item "storage.vsan" "storage" "storage/vsan.log" "$_vs_disp" "true" \
            "$_vs_siso" "$_vs_sep" 124 "timeout" "$CMD_TIMEOUT_SEC" "$_vs_cl" "timed out after ${CMD_TIMEOUT_SEC}s"
        return 0
    fi
    if is_perm_err_file "$_vs_cl"; then
        finalize_item "storage.vsan" "storage" "storage/vsan.log" "$_vs_disp" "true" \
            "$_vs_siso" "$_vs_sep" "$_vs_rc" "permission_denied" "$CMD_TIMEOUT_SEC" "$_vs_cl" "permission denied (uid=${RUN_AS_UID})"
        return 0
    fi

    _vs_enabled=0
    if [ "$_vs_rc" -eq 0 ] && grep -iE '^[ \t]*enabled[ \t]*:[ \t]*true' "$_vs_cl" >/dev/null 2>&1; then
        _vs_enabled=1
    elif [ "$_vs_rc" -eq 0 ] && grep -iE 'sub-cluster uuid[ \t]*:[ \t]*[0-9a-f-]+' "$_vs_cl" >/dev/null 2>&1 \
        && ! grep -iE 'sub-cluster uuid[ \t]*:[ \t]*0+(-0+)*[ \t]*$' "$_vs_cl" >/dev/null 2>&1 \
        && ! grep -iE 'not enabled|enabled[ \t]*:[ \t]*false' "$_vs_cl" >/dev/null 2>&1; then
        _vs_enabled=1
    fi

    if [ "$_vs_enabled" -eq 0 ]; then
        finalize_item "storage.vsan" "storage" "storage/vsan.log" "$_vs_disp" "true" \
            "$_vs_siso" "$_vs_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_vs_cl" "vSAN is not enabled on this host"
        return 0
    fi

    printf '## esxcli vsan cluster get\n' >> "$_vs_comb"
    cat "$_vs_cl" >> "$_vs_comb"
    printf '\n' >> "$_vs_comb"

    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_vs_hl" "esxcli vsan health cluster list"
    _hl_rc=$?
    printf '## esxcli vsan health cluster list\n' >> "$_vs_comb"
    cat "$_vs_hl" >> "$_vs_comb"
    printf '\n' >> "$_vs_comb"

    _vs_st="ok"; _vs_note=""
    if [ "$_hl_rc" -eq 124 ]; then
        _vs_st="timeout"; _vs_rc=124; _vs_note="esxcli vsan health cluster list timed out after ${CMD_TIMEOUT_SEC}s"
    else
        _vs_rc=0
    fi
    finalize_item "storage.vsan" "storage" "storage/vsan.log" "$_vs_disp" "true" \
        "$_vs_siso" "$_vs_sep" "$_vs_rc" "$_vs_st" "$CMD_TIMEOUT_SEC" "$_vs_comb" "$_vs_note"
}

# Read-only VM snapshot summary across registered VMs with total time budget & VM cap.
collect_vm_snapshots() {
    _sn_siso=$(iso_now_raw); _sn_sep=$(now_epoch)
    _sn_out="${SCRATCH_DIR}/vm_snaps.tmp"
    _sn_body="${SCRATCH_DIR}/vm_snaps_body.tmp"
    _sn_sub="${SCRATCH_DIR}/vm_snap_sub.tmp"
    _sn_list="${SCRATCH_DIR}/vm_snap_ids.tmp"
    : > "$_sn_out"; : > "$_sn_body"; : > "$_sn_list"
    _sn_disp="for VMID in vim-cmd vmsvc/getallvms; do vim-cmd vmsvc/snapshot.get \$VMID; done (summary of VMs with snapshots)"

    if ! command -v vim-cmd >/dev/null 2>&1; then
        finalize_item "vms.snapshots" "vms" "vms/snapshots.log" "$_sn_disp" "true" \
            "$_sn_siso" "$_sn_sep" 127 "command_missing" "$SNAPSHOT_TOTAL_TIMEOUT" "$_sn_out" "command not found: vim-cmd"
        return 0
    fi

    _vm_log="${CFGDIR}/vms/vm-list.log"
    if [ -r "$_vm_log" ]; then
        if grep -q '^\[permission denied:' "$_vm_log" 2>/dev/null; then
            finalize_item "vms.snapshots" "vms" "vms/snapshots.log" "$_sn_disp" "true" \
                "$_sn_siso" "$_sn_sep" 1 "permission_denied" "$SNAPSHOT_TOTAL_TIMEOUT" "$_sn_out" "vim-cmd vmsvc/getallvms permission denied"
            return 0
        fi
        awk '$1 ~ /^[0-9]+$/ {
            id = $1
            name = (NF >= 2 ? $2 : "unknown")
            if (!seen[id]++) printf "%s %s\n", id, name
        }' "$_vm_log" > "$_sn_list" 2>/dev/null
    fi

    _vm_total=$(wc -l < "$_sn_list" 2>/dev/null | tr -d ' \t\r\n')
    [ -z "$_vm_total" ] && _vm_total=0
    _vm_checked=0; _vm_with_snap=0; _vm_to_cnt=0
    _trunc_limit="false"; _trunc_time="false"

    _per_to="$CMD_TIMEOUT_SEC"
    [ "$_per_to" -gt 10 ] && _per_to=10

    while read -r _vid _vname; do
        [ -n "$_vid" ] || continue
        case "$_vid" in
            *[!0-9]*) continue ;;
        esac
        if [ "$_vm_checked" -ge "$MAX_SNAPSHOT_VMS" ]; then
            _trunc_limit="true"
            break
        fi
        _now_ep=$(now_epoch)
        _elapsed=$((_now_ep - _sn_sep))
        if [ "$SNAPSHOT_TOTAL_TIMEOUT" -gt 0 ] && [ "$_elapsed" -ge "$SNAPSHOT_TOTAL_TIMEOUT" ]; then
            _trunc_time="true"
            break
        fi
        _rem=$((SNAPSHOT_TOTAL_TIMEOUT - _elapsed))
        _cur_to="$_per_to"
        [ "$_rem" -lt "$_cur_to" ] && _cur_to="$_rem"
        [ "$_cur_to" -lt 1 ] && _cur_to=1

        _vm_checked=$((_vm_checked + 1))
        : > "$_sn_sub"
        exec_with_timeout "$_cur_to" "$_sn_sub" "vim-cmd vmsvc/snapshot.get \"${_vid}\""
        _vrc=$?
        if [ "$_vrc" -eq 124 ]; then
            _vm_to_cnt=$((_vm_to_cnt + 1))
            printf '## vmid=%s name=%s (timeout after %ss)\n' "$_vid" "$_vname" "$_cur_to" >> "$_sn_body"
            continue
        fi
        if [ "$_vrc" -eq 0 ] && [ -s "$_sn_sub" ]; then
            if ! grep -iE 'no snapshots|does not have any snapshots' "$_sn_sub" >/dev/null 2>&1 \
                && grep -E 'Snapshot Name|Snapshot Id|Snapshot Created On|\|--' "$_sn_sub" >/dev/null 2>&1; then
                _vm_with_snap=$((_vm_with_snap + 1))
                printf '## vmid=%s name=%s\n' "$_vid" "$_vname" >> "$_sn_body"
                cat "$_sn_sub" >> "$_sn_body"
                printf '\n' >> "$_sn_body"
            fi
        fi
    done < "$_sn_list"

    {
        printf 'vm_total=%s\n' "$_vm_total"
        printf 'vms_checked=%s\n' "$_vm_checked"
        printf 'vms_with_snapshots=%s\n' "$_vm_with_snap"
        printf 'vms_timeout=%s\n' "$_vm_to_cnt"
        printf 'max_snapshot_vms=%s\n' "$MAX_SNAPSHOT_VMS"
        printf 'snapshot_total_timeout_sec=%s\n' "$SNAPSHOT_TOTAL_TIMEOUT"
        printf 'truncated_by_vm_limit=%s\n' "$_trunc_limit"
        printf 'truncated_by_total_timeout=%s\n' "$_trunc_time"
        if [ -s "$_sn_body" ]; then
            printf '\n'
            cat "$_sn_body"
        else
            printf '\n(no VM snapshots detected)\n'
        fi
    } > "$_sn_out"

    _sn_st="ok"; _sn_rc=0; _sn_note=""
    if [ "$_trunc_time" = "true" ]; then
        _sn_note="stopped after ${SNAPSHOT_TOTAL_TIMEOUT}s total snapshot budget (${_vm_checked}/${_vm_total} VMs checked)"
    elif [ "$_trunc_limit" = "true" ]; then
        _sn_note="capped at ${MAX_SNAPSHOT_VMS} VMs (${_vm_total} total registered)"
    fi
    finalize_item "vms.snapshots" "vms" "vms/snapshots.log" "$_sn_disp" "true" \
        "$_sn_siso" "$_sn_sep" "$_sn_rc" "$_sn_st" "$SNAPSHOT_TOTAL_TIMEOUT" "$_sn_out" "$_sn_note"
}

# ── Section 1: system ──
echo "Collecting system information ..."
run_multi "system.version" "system" "system/version.log" "false" "$CMD_TIMEOUT_SEC" \
    "vmware -vl; esxcli system version get" \
    "vmware::vmware -vl" "esxcli::esxcli system version get"
run_cmd "system.hostname" "system" "system/hostname.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli system hostname get" "esxcli" "esxcli system hostname get"
run_multi "system.uptime" "system" "system/uptime.log" "false" "$CMD_TIMEOUT_SEC" \
    "uptime; esxcli system stats uptime get" \
    "uptime::uptime" "esxcli::esxcli system stats uptime get"
run_cmd "system.boot" "system" "system/boot.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli system boot device get" "esxcli" "esxcli system boot device get"
collect_boot_health
run_multi "system.time" "system" "system/time.log" "false" "$CMD_TIMEOUT_SEC" \
    "esxcli system time get; esxcli system ntp get" \
    "esxcli::esxcli system time get" "esxcli::esxcli system ntp get"
run_cmd "system.syslog_config" "system" "system/syslog-config.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli system syslog config get" "esxcli" "esxcli system syslog config get"
collect_ssl_cert
collect_security_mode
run_cmd "system.modules" "system" "system/modules.log" "false" "$CMD_TIMEOUT_SEC" "head:60" \
    "esxcli system module list | head -n 60" "esxcli" "esxcli system module list"
run_multi "system.services" "system" "system/services.log" "false" "$CMD_TIMEOUT_SEC" \
    "chkconfig --list; /etc/init.d/hostd status; /etc/init.d/vpxa status" \
    "chkconfig::chkconfig --list" \
    "${ROOT_PREFIX}/etc/init.d/hostd::${ROOT_PREFIX}/etc/init.d/hostd status" \
    "${ROOT_PREFIX}/etc/init.d/vpxa::${ROOT_PREFIX}/etc/init.d/vpxa status"
run_cmd "system.advanced_changed" "system" "system/advanced-changed.log" "true" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli system settings advanced list -d" "esxcli" "esxcli system settings advanced list -d"

# ── Section 2: hardware ──
echo "Collecting hardware information ..."
run_cmd "hardware.platform" "hardware" "hardware/platform.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli hardware platform get" "esxcli" "esxcli hardware platform get"
run_multi "hardware.cpu" "hardware" "hardware/cpu.log" "false" "$CMD_TIMEOUT_SEC" \
    "esxcli hardware cpu global get; esxcli hardware cpu list | head -n 80" \
    "esxcli::esxcli hardware cpu global get" "esxcli::esxcli hardware cpu list::head:80"
run_cmd "hardware.memory" "hardware" "hardware/memory.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli hardware memory get" "esxcli" "esxcli hardware memory get"
run_cmd "hardware.pci" "hardware" "hardware/pci.log" "false" "$CMD_TIMEOUT_SEC" "head:400" \
    "esxcli hardware pci list | head -n 400" "esxcli" "esxcli hardware pci list"
run_cmd "hardware.bootdevice" "hardware" "hardware/bootdevice.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli hardware bootdevice list" "esxcli" "esxcli hardware bootdevice list"
run_cmd "hardware.ipmi_sel" "hardware" "hardware/ipmi-sel.log" "true" "$CMD_TIMEOUT_SEC" "head:200" \
    "esxcli hardware ipmi sel list | head -n 200" "esxcli" "esxcli hardware ipmi sel list"
run_cmd "hardware.ipmi_sdr" "hardware" "hardware/ipmi-sdr.log" "true" "$CMD_TIMEOUT_SEC" "head:200" \
    "esxcli hardware ipmi sdr list | head -n 200" "esxcli" "esxcli hardware ipmi sdr list"

# ── Section 3: storage ──
echo "Collecting storage information ..."
run_cmd "storage.adapters" "storage" "storage/adapters.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli storage core adapter list" "esxcli" "esxcli storage core adapter list"
run_cmd "storage.devices" "storage" "storage/devices.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli storage core device list" "esxcli" "esxcli storage core device list"
run_cmd "storage.device_stats" "storage" "storage/device-stats.log" "false" "$CMD_TIMEOUT_SEC" "head:200" \
    "esxcli storage core device stats get | head -n 200" "esxcli" "esxcli storage core device stats get"
run_cmd "storage.paths" "storage" "storage/paths.log" "false" "$CMD_TIMEOUT_SEC" "head:300" \
    "esxcli storage core path list | head -n 300" "esxcli" "esxcli storage core path list"
run_cmd "storage.nmp" "storage" "storage/nmp.log" "false" "$CMD_TIMEOUT_SEC" "head:200" \
    "esxcli storage nmp device list | head -n 200" "esxcli" "esxcli storage nmp device list"
run_multi "storage.vmfs" "storage" "storage/vmfs.log" "false" "$CMD_TIMEOUT_SEC" \
    "esxcli storage vmfs extent list; esxcli storage filesystem list" \
    "esxcli::esxcli storage vmfs extent list" "esxcli::esxcli storage filesystem list"
run_cmd "storage.df" "storage" "storage/df.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "df -h" "df" "df -h"
run_cmd "storage.scsidevs" "storage" "storage/scsidevs.log" "false" "$CMD_TIMEOUT_SEC" "head:300" \
    "esxcfg-scsidevs -l | head -n 300" "esxcfg-scsidevs" "esxcfg-scsidevs -l"

# ── Hardware RAID Controller & Management Tool Detection / Collection (BusyBox ash safe) ──

RAID_CONTROLLER_DETECTED="false"
RAID_HAS_DELL_PERC=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_ESXCLI=""

find_esxi_raid_bin() {
    _fr_names="$1"
    _fr_extras="$2"
    _fr_oldifs="$IFS"
    IFS=','
    for _fr_c in $_fr_names; do
        [ -n "$_fr_c" ] || continue
        _fr_r=$(command -v "$_fr_c" 2>/dev/null || true)
        if [ -n "$_fr_r" ] && [ -x "$_fr_r" ] && [ ! -d "$_fr_r" ]; then
            IFS="$_fr_oldifs"
            case "$_fr_r" in
                /*) printf '%s' "$_fr_r" ;;
                *)  printf '%s/%s' "$(pwd)" "${_fr_r#./}" ;;
            esac
            return 0
        fi
    done
    if [ -n "$ROOT_PREFIX" ] || [ "${ITCHECK_KEEP_PATH:-0}" != "1" ]; then
        for _fr_c in $_fr_extras; do
            [ -n "$_fr_c" ] || continue
            _fr_r="${ROOT_PREFIX}${_fr_c}"
            if [ -x "$_fr_r" ] && [ ! -d "$_fr_r" ]; then
                IFS="$_fr_oldifs"
                printf '%s' "$_fr_r"
                return 0
            fi
        done
    fi
    IFS="$_fr_oldifs"
    return 1
}

logical_esxi_bin() {
    _lb_p="$1"
    [ -n "$_lb_p" ] || return 0
    if [ -n "$ROOT_PREFIX" ]; then
        case "$_lb_p" in
            "${ROOT_PREFIX}"/*) _lb_p="${_lb_p#"$ROOT_PREFIX"}" ;;
        esac
    fi
    if [ "${ITCHECK_KEEP_PATH:-0}" = "1" ]; then
        case "$_lb_p" in
            /opt/*|/usr/*|/sbin/*|/bin/*) ;;
            *) _lb_p=$(basename "$_lb_p") ;;
        esac
    fi
    printf '%s' "$_lb_p"
}

probe_esxi_tool_ver() {
    _pv_name="$1"
    _pv_bin="$2"
    [ -n "$_pv_bin" ] || return 0
    _pv_tmp="${SCRATCH_DIR}/raid_ver.tmp"
    : > "$_pv_tmp"
    _pv_cmd=""
    case "$_pv_name" in
        storcli|perccli) _pv_cmd="cd \"${SCRATCH_DIR}\" && \"${_pv_bin}\" -v" ;;
        megacli)         _pv_cmd="cd \"${SCRATCH_DIR}\" && \"${_pv_bin}\" -v -NoLog" ;;
        arcconf)         _pv_cmd="cd \"${SCRATCH_DIR}\" && \"${_pv_bin}\" VERSION" ;;
        ssacli)          _pv_cmd="cd \"${SCRATCH_DIR}\" && \"${_pv_bin}\" version" ;;
        *) return 0 ;;
    esac
    exec_with_timeout 5 "$_pv_tmp" "$_pv_cmd"
    if [ $? -eq 0 ] && [ -s "$_pv_tmp" ] && ! is_perm_err_file "$_pv_tmp"; then
        awk '
        /^[ \t]*$/ { next }
        tolower($0) ~ /(ver|version|storcli|perccli|megacli|arcconf|ssacli)/ {
            gsub(/^[ \t]+|[ \t]+$/, "")
            gsub(/[|]/, " ")
            print substr($0, 1, 100)
            exit
        }' "$_pv_tmp" 2>/dev/null || true
    fi
}

run_esxi_raid_cmd() {
    _er_id="$1"; _er_rel="$2"; _er_disp="$3"; _er_fout="$4"; _er_na="$5"; _er_cmd="$6"
    _er_siso=$(iso_now_raw)
    _er_sep=$(now_epoch)
    _er_raw="${SCRATCH_DIR}/raid_raw.tmp"
    _er_body="${SCRATCH_DIR}/raid_body.tmp"
    : > "$_er_raw"
    : > "$_er_body"
    [ -n "$_er_fout" ] && rm -f "$_er_fout" 2>/dev/null

    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_er_raw" "cd \"${SCRATCH_DIR}\" && ${_er_cmd}"
    _er_rc=$?
    if [ -n "$_er_fout" ] && [ -s "$_er_fout" ]; then
        cp "$_er_fout" "$_er_body" 2>/dev/null
        rm -f "$_er_fout" 2>/dev/null
    else
        [ -n "$_er_fout" ] && rm -f "$_er_fout" 2>/dev/null
        cp "$_er_raw" "$_er_body" 2>/dev/null
    fi

    _er_note=""
    if [ "$_er_na" = "bbu_cv" ] && grep -iE 'use /c[x0-9]+/(cv|bbu)|battery is absent|cachevault is absent|bbu is not present|no bbu|not supported|number of controllers[ \t]*=[ \t]*0|controller not found|no controller|adapter[ \t]*0.*not found' "$_er_body" >/dev/null 2>&1; then
        _er_st="not_applicable"
        _er_note="not present or not applicable on this controller"
    elif [ "$_er_na" = "ctrl_zero" ] && grep -iE 'number of controllers[ \t]*=[ \t]*0|no controller|controller not found|no lsi sas|no adapters found|error:[ \t]*no controllers' "$_er_body" >/dev/null 2>&1; then
        _er_st="not_applicable"
        _er_note="no matching RAID controller detected by tool"
    else
        _er_st=$(classify_status "$_er_rc" "true" "$_er_body")
        [ "$_er_st" = "permission_denied" ] && _er_note="permission denied (uid=${RUN_AS_UID})"
        [ "$_er_st" = "timeout" ] && _er_note="timed out after ${CMD_TIMEOUT_SEC}s"
    fi

    finalize_item "$_er_id" "storage" "$_er_rel" "$_er_disp" "true" \
        "$_er_siso" "$_er_sep" "$_er_rc" "$_er_st" "$CMD_TIMEOUT_SEC" "$_er_body" "$_er_note"
}

collect_esxi_raid_detect() {
    _rd_siso=$(iso_now_raw)
    _rd_sep=$(now_epoch)
    _rd_pci="${SCRATCH_DIR}/esxi_raid_pci.tmp"
    _rd_adp="${SCRATCH_DIR}/esxi_raid_adp.tmp"
    _rd_ctrls="${SCRATCH_DIR}/esxi_raid_ctrls.tmp"
    _rd_drvs="${SCRATCH_DIR}/esxi_raid_drvs.tmp"
    _rd_out="${SCRATCH_DIR}/esxi_raid_detect.tmp"
    : > "$_rd_pci"; : > "$_rd_adp"; : > "$_rd_ctrls"; : > "$_rd_drvs"; : > "$_rd_out"

    if command -v esxcli >/dev/null 2>&1; then
        RAID_BIN_ESXCLI=$(command -v esxcli 2>/dev/null || true)
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_rd_pci" "esxcli hardware pci list"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_rd_adp" "esxcli storage core adapter list"
    fi

    if [ -s "$_rd_pci" ]; then
        awk '
        function classify_fam(cls, vid, svid, drv, low_all) {
            if ((drv ~ /^(lsi_mr3|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 ~ /^(lsi_mr3|megaraid)/ || (vid == "1000" && (cls == "0104" || low_all ~ /(megaraid|raid|3108|3508|3516|3908|3916|2208|2108|3808|3816)/))) return "megaraid"
            if (drv ~ /^(nhpsa|hpsa|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|aacraid_esx|smartpqi)$/ || vid == "9005" || vid == "11f8" || low_all ~ /(adaptec|microsemi|microchip|smartraid|pmc-sierra)/) return "arcconf"
            if (drv == "spraid" || (vid == "19e5" && (cls == "0104" || low_all ~ /(raid|hi1880|spraid)/))) return "huawei_spraid"
            if (drv ~ /^(lsi_msgpt|mpt|mpi3mr)/ || (vid == "1000" && (cls == "0107" || low_all ~ /(sas2008|sas2308|sas3008|sas3408|sas3808|fusion-mpt)/))) return "lsi_ir"
            if (vid == "8086" && (cls == "0104" || low_all ~ /(vmd|volume management|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_drv(d) {
            return (d ~ /^(lsi_mr3|megaraid_sas|megaraid_mbox|lsi_msgpt3|lsi_msgpt35|lsi_msgpt2|mpi3mr|smartpqi|nhpsa|hpsa|cciss|aacraid|aacraid_esx|spraid|arcmsr|3w-9xxx|3w_9xxx)$/)
        }
        function norm_hex4(v,   s) {
            s = tolower(v); sub(/^0x/, "", s); gsub(/[^0-9a-f]/, "", s)
            while (length(s) > 4 && substr(s, 1, 1) == "0") s = substr(s, 2)
            return substr(s, 1, 4)
        }
        function flush_pci(   low_all, is_virt, hit, fam, dsc) {
            if (bdf == "") return
            low_all = tolower(cls_name " " vname " " dname " " svname " " mod)
            is_virt = (low_all ~ /(vmware|virtio|qemu|xen|hyper-v|red hat)/)
            hit = 0
            if (is_raid_drv(mod)) hit = 1
            else if (!is_virt && (cls == "0104" || tolower(cls_name) ~ /raid/)) hit = 1
            else if (!is_virt && cls == "0107" && (vid == "1000" || vid == "9005" || vid == "103c" || vid == "19e5")) hit = 1
            if (hit) {
                fam = classify_fam(cls, vid, svid, mod, low_all)
                dsc = vname " " dname
                if (svname != "") dsc = dsc " (" svname ")"
                gsub(/^[ \t]+|[ \t]+$/, "", dsc)
                gsub(/[|]/, " ", dsc)
                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, cls, vid, did, svid, mod, fam, dsc
            }
            bdf=""; cls=""; cls_name=""; vid=""; did=""; svid=""; vname=""; dname=""; svname=""; 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][ \t]*$/ {
            flush_pci()
            bdf = $1
            next
        }
        /^[ \t]+Device Class:/      { sub(/^[^:]+:[ \t]*/, ""); cls = norm_hex4($0); next }
        /^[ \t]+Device Class Name:/ { sub(/^[^:]+:[ \t]*/, ""); cls_name = $0; next }
        /^[ \t]+Vendor ID:/         { sub(/^[^:]+:[ \t]*/, ""); vid = norm_hex4($0); next }
        /^[ \t]+Device ID:/         { sub(/^[^:]+:[ \t]*/, ""); did = norm_hex4($0); next }
        /^[ \t]+SubVendor ID:/      { sub(/^[^:]+:[ \t]*/, ""); svid = norm_hex4($0); next }
        /^[ \t]+Vendor Name:/       { sub(/^[^:]+:[ \t]*/, ""); vname = $0; next }
        /^[ \t]+Device Name:/       { sub(/^[^:]+:[ \t]*/, ""); dname = $0; next }
        /^[ \t]+SubVendor Name:/    { sub(/^[^:]+:[ \t]*/, ""); svname = $0; next }
        /^[ \t]+Module Name:/       { sub(/^[^:]+:[ \t]*/, ""); mod = $1; next }
        END { flush_pci() }
        ' "$_rd_pci" > "$_rd_ctrls" 2>/dev/null
    fi

    # Extract active RAID drivers from esxcli storage core adapter list
    if [ -s "$_rd_adp" ]; then
        awk 'NR>2 && $2 ~ /^(lsi_mr3|megaraid_sas|megaraid_mbox|lsi_msgpt3|lsi_msgpt35|lsi_msgpt2|mpi3mr|smartpqi|nhpsa|hpsa|cciss|aacraid|aacraid_esx|spraid|arcmsr|3w-9xxx|3w_9xxx)$/ { print $2 }' "$_rd_adp" 2>/dev/null >> "$_rd_drvs"
    fi
    if [ -s "$_rd_ctrls" ]; then
        awk -F'|' '{ for (i=1; i<=NF; i++) if ($i ~ /driver=/) { s=$i; sub(/^.*driver=/,"",s); gsub(/[ \t]/,"",s); if (s!="") print s } }' "$_rd_ctrls" >> "$_rd_drvs"
    fi
    if [ -s "$_rd_drvs" ]; then
        LC_ALL=C sort -u "$_rd_drvs" > "${_rd_drvs}.u" && mv "${_rd_drvs}.u" "$_rd_drvs"
    fi
    if [ ! -s "$_rd_ctrls" ] && [ -s "$_rd_drvs" ]; then
        _didx=0
        while IFS= read -r _dn; do
            [ -n "$_dn" ] || continue
            case "$_dn" in
                lsi_mr3|megaraid_*) _df="megaraid" ;;
                nhpsa|hpsa|cciss) _df="hpe_ssa" ;;
                aacraid*|smartpqi) _df="arcconf" ;;
                lsi_msgpt*|mpi3mr) _df="lsi_ir" ;;
                spraid) _df="huawei_spraid" ;;
                *) _df="generic_raid" ;;
            esac
            printf 'controller=%d | bdf=unknown | pci_class= | vendor_id= | device_id= | subsys_vendor= | driver=%s | family=%s | description=Detected via ESXi adapter driver %s\n' \
                "$_didx" "$_dn" "$_df" "$_dn" >> "$_rd_ctrls"
            _didx=$((_didx + 1))
        done < "$_rd_drvs"
    fi

    RAID_BIN_STORCLI=$(find_esxi_raid_bin "storcli,storcli64,storcli2" \
        "/opt/lsi/storcli/storcli,/opt/lsi/storcli/storcli64,/opt/lsi/storcli2/storcli2,/opt/MegaRAID/storcli/storcli64,/opt/MegaRAID/storcli/storcli" || true)
    RAID_BIN_PERCCLI=$(find_esxi_raid_bin "perccli,perccli64,perccli2" \
        "/opt/lsi/perccli/perccli,/opt/lsi/perccli/perccli64,/opt/lsi/perccli2/perccli2,/opt/dell/perccli/perccli,/opt/MegaRAID/perccli/perccli64" || true)
    RAID_BIN_MEGACLI=$(find_esxi_raid_bin "MegaCli,MegaCli64,megacli" \
        "/opt/lsi/MegaCLI/MegaCli,/opt/lsi/MegaCLI/MegaCli64,/opt/MegaRAID/MegaCli/MegaCli64" || true)
    RAID_BIN_ARCCONF=$(find_esxi_raid_bin "arcconf,ARCCONF" \
        "/opt/arcconf/arcconf,/opt/microsemi/arcconf/arcconf,/opt/microchip/arcconf/arcconf,/opt/adaptec/arcconf/arcconf" || true)
    RAID_BIN_SSACLI=$(find_esxi_raid_bin "ssacli,hpssacli,hpacucli" \
        "/opt/smartstorageadmin/ssacli/bin/ssacli,/opt/hp/hpssacli/bin/hpssacli,/opt/smartstorageadmin/ssacli/bin/ssacli64" || true)
    RAID_BIN_SAS3IRCU=$(find_esxi_raid_bin "sas3ircu" "/opt/lsi/sas3ircu/sas3ircu" || true)
    RAID_BIN_SAS2IRCU=$(find_esxi_raid_bin "sas2ircu" "/opt/lsi/sas2ircu/sas2ircu" || true)

    _ccnt=0
    if [ -s "$_rd_ctrls" ]; then
        _ccnt=$(wc -l < "$_rd_ctrls" | tr -d ' \t\r\n')
        [ "${_ccnt:-0}" -gt 0 ] && RAID_CONTROLLER_DETECTED="true"
    fi
    grep 'family=dell_perc' "$_rd_ctrls" >/dev/null 2>&1 && RAID_HAS_DELL_PERC=1
    grep 'family=arcconf' "$_rd_ctrls" >/dev/null 2>&1 && RAID_HAS_ARCCONF=1

    _fams="none"; _drvs_csv="none"; _inst_raid="none"; _rtool_avail="false"; _esx_smart="false"
    if [ -s "$_rd_ctrls" ]; then
        _fams=$(awk -F'|' '{ for (i=1; i<=NF; i++) if ($i ~ /family=/) { s=$i; sub(/^.*family=/,"",s); gsub(/[ \t]/,"",s); if (s!="") print s } }' "$_rd_ctrls" | LC_ALL=C sort -u | awk '{ o=(o==""?$0:o","$0) } END { print o }')
        [ -z "$_fams" ] && _fams="none"
    fi
    if [ -s "$_rd_drvs" ]; then
        _drvs_csv=$(awk '{ o=(o==""?$0:o","$0) } END { print o }' "$_rd_drvs")
        [ -z "$_drvs_csv" ] && _drvs_csv="none"
    fi
    _tl=""
    [ -n "$RAID_BIN_STORCLI" ]  && _tl="${_tl:+${_tl},}storcli"
    [ -n "$RAID_BIN_PERCCLI" ]  && _tl="${_tl:+${_tl},}perccli"
    [ -n "$RAID_BIN_MEGACLI" ]  && _tl="${_tl:+${_tl},}megacli"
    [ -n "$RAID_BIN_ARCCONF" ]  && _tl="${_tl:+${_tl},}arcconf"
    [ -n "$RAID_BIN_SSACLI" ]   && _tl="${_tl:+${_tl},}ssacli"
    [ -n "$RAID_BIN_SAS3IRCU" ] && _tl="${_tl:+${_tl},}sas3ircu"
    [ -n "$RAID_BIN_SAS2IRCU" ] && _tl="${_tl:+${_tl},}sas2ircu"
    if [ -n "$_tl" ]; then
        _rtool_avail="true"
        _inst_raid="$_tl"
    fi
    [ -n "$RAID_BIN_ESXCLI" ] && _esx_smart="true"

    {
        printf 'raid_controller_detected=%s\n' "$RAID_CONTROLLER_DETECTED"
        printf 'raid_controller_count=%s\n' "${_ccnt:-0}"
        printf 'raid_tool_available=%s\n' "$_rtool_avail"
        printf 'smartctl_available=%s\n' "$_esx_smart"
        printf 'detected_families=%s\n' "$_fams"
        printf 'active_raid_drivers=%s\n' "$_drvs_csv"
        printf 'installed_raid_tools=%s\n' "$_inst_raid"
        printf '\n## detected_controllers\n'
        if [ -s "$_rd_ctrls" ]; then cat "$_rd_ctrls"; else printf 'none\n'; fi
        printf '\n## loaded_raid_drivers\n'
        if [ -s "$_rd_drvs" ]; then cat "$_rd_drvs"; else printf 'none\n'; fi
        printf '\n## tool_inventory\n'
        for _tn in storcli perccli megacli arcconf ssacli sas3ircu sas2ircu esxcli_smart; do
            case "$_tn" in
                storcli)      _tb="$RAID_BIN_STORCLI" ;;
                perccli)      _tb="$RAID_BIN_PERCCLI" ;;
                megacli)      _tb="$RAID_BIN_MEGACLI" ;;
                arcconf)      _tb="$RAID_BIN_ARCCONF" ;;
                ssacli)       _tb="$RAID_BIN_SSACLI" ;;
                sas3ircu)     _tb="$RAID_BIN_SAS3IRCU" ;;
                sas2ircu)     _tb="$RAID_BIN_SAS2IRCU" ;;
                esxcli_smart) _tb="$RAID_BIN_ESXCLI" ;;
            esac
            if [ -n "$_tb" ]; then
                _ti="true"
                _tv=$(probe_esxi_tool_ver "$_tn" "$_tb")
                _td=$(logical_esxi_bin "$_tb")
            else
                _ti="false"; _tv=""; _td=""
            fi
            printf 'tool=%s | installed=%s | path=%s | version=%s\n' "$_tn" "$_ti" "$_td" "$_tv"
        done
    } > "$_rd_out"

    finalize_item "storage.raid_detect" "storage" "storage/raid-detect.log" \
        "RAID controller & management tool detection (esxcli hardware pci / storage adapter + StorCLI/PercCLI/MegaCLI/ARCCONF/SSACLI/SASxIRCU)" \
        "false" "$_rd_siso" "$_rd_sep" 0 "ok" "$CMD_TIMEOUT_SEC" "$_rd_out" ""
}

collect_esxi_storcli_family() {
    _cs_tag="$1"; _cs_bin="$2"
    _cs_dbin=$(logical_esxi_bin "$_cs_bin")
    _cs_evt="${SCRATCH_DIR}/raid_${_cs_tag}_events.tmp"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_show_all" "storage/raid-${_cs_tag}-show-all.log" "${_cs_dbin} /call show all" "" "ctrl_zero" "\"${_cs_bin}\" /call show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_bbu" "storage/raid-${_cs_tag}-bbu.log" "${_cs_dbin} /call/bbu show all" "" "bbu_cv" "\"${_cs_bin}\" /call/bbu show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_cv" "storage/raid-${_cs_tag}-cv.log" "${_cs_dbin} /call/cv show all" "" "bbu_cv" "\"${_cs_bin}\" /call/cv show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_dall" "storage/raid-${_cs_tag}-dall.log" "${_cs_dbin} /call/dall show all" "" "ctrl_zero" "\"${_cs_bin}\" /call/dall show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_eall" "storage/raid-${_cs_tag}-eall.log" "${_cs_dbin} /call/eall show all" "" "ctrl_zero" "\"${_cs_bin}\" /call/eall show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_sall" "storage/raid-${_cs_tag}-sall.log" "${_cs_dbin} /call/eall/sall show all" "" "ctrl_zero" "\"${_cs_bin}\" /call/eall/sall show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_vall" "storage/raid-${_cs_tag}-vall.log" "${_cs_dbin} /call/vall show all" "" "ctrl_zero" "\"${_cs_bin}\" /call/vall show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_pall" "storage/raid-${_cs_tag}-pall.log" "${_cs_dbin} /call/pall show all" "" "ctrl_zero" "\"${_cs_bin}\" /call/pall show all"
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_events" "storage/raid-${_cs_tag}-events.log" "${_cs_dbin} /call show events file=<tmp>" "$_cs_evt" "ctrl_zero" "\"${_cs_bin}\" /call show events \"file=${_cs_evt}\""
    run_esxi_raid_cmd "storage.raid_${_cs_tag}_termlog" "storage/raid-${_cs_tag}-termlog.log" "${_cs_dbin} /call show termlog" "" "ctrl_zero" "\"${_cs_bin}\" /call show termlog"
}

collect_esxi_megacli() {
    _cm_bin="$1"
    _cm_dbin=$(logical_esxi_bin "$_cm_bin")
    _cm_evt="${SCRATCH_DIR}/raid_megacli_events.tmp"
    run_esxi_raid_cmd "storage.raid_megacli_adpallinfo" "storage/raid-megacli-adpallinfo.log" "${_cm_dbin} -AdpAllInfo -aALL -NoLog" "" "ctrl_zero" "\"${_cm_bin}\" -AdpAllInfo -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_encinfo" "storage/raid-megacli-encinfo.log" "${_cm_dbin} -EncInfo -aALL -NoLog" "" "ctrl_zero" "\"${_cm_bin}\" -EncInfo -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_pdlist" "storage/raid-megacli-pdlist.log" "${_cm_dbin} -PDList -aALL -NoLog" "" "ctrl_zero" "\"${_cm_bin}\" -PDList -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_ldinfo" "storage/raid-megacli-ldinfo.log" "${_cm_dbin} -LDInfo -Lall -aALL -NoLog" "" "ctrl_zero" "\"${_cm_bin}\" -LDInfo -Lall -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_ldpdinfo" "storage/raid-megacli-ldpdinfo.log" "${_cm_dbin} -LdPdInfo -aALL -NoLog" "" "ctrl_zero" "\"${_cm_bin}\" -LdPdInfo -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_bbu" "storage/raid-megacli-bbu.log" "${_cm_dbin} -AdpBbuCmd -aALL -NoLog" "" "bbu_cv" "\"${_cm_bin}\" -AdpBbuCmd -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_phyerr" "storage/raid-megacli-phyerr.log" "${_cm_dbin} -PhyErrorCounters -aALL -NoLog" "" "ctrl_zero" "\"${_cm_bin}\" -PhyErrorCounters -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_events" "storage/raid-megacli-events.log" "${_cm_dbin} -AdpEventLog -GetEvents -f <tmp> -aALL -NoLog" "$_cm_evt" "ctrl_zero" "\"${_cm_bin}\" -AdpEventLog -GetEvents -f \"${_cm_evt}\" -aALL -NoLog"
    run_esxi_raid_cmd "storage.raid_megacli_fwtermlog" "storage/raid-megacli-fwtermlog.log" "${_cm_dbin} -FwTermLog Dsply -aALL -NoLog" "" "ctrl_zero" "\"${_cm_bin}\" -FwTermLog Dsply -aALL -NoLog"
}

collect_esxi_arcconf() {
    _ca_bin="$1"
    _ca_dbin=$(logical_esxi_bin "$_ca_bin")
    run_esxi_raid_cmd "storage.raid_arcconf_list" "storage/raid-arcconf-list.log" "${_ca_dbin} LIST" "" "ctrl_zero" "\"${_ca_bin}\" LIST"
    _ca_lf="${CFGDIR}/storage/raid-arcconf-list.log"
    _ca_cids=""
    if [ -r "$_ca_lf" ]; then
        _ca_cids=$(awk '/Controller[ \t]+[0-9]+/ { if (match($0, /Controller[ \t]+[0-9]+/)) { s=substr($0,RSTART,RLENGTH); sub(/^Controller[ \t]+/,"",s); if (!seen[s]++) print s } }' "$_ca_lf" 2>/dev/null | tr '\n' ' ')
    fi
    if [ -z "$(printf '%s' "$_ca_cids" | tr -d ' \t\r\n')" ] && [ "$RAID_HAS_ARCCONF" -eq 1 ]; then
        _ca_cids="1"
    fi
    if [ -n "$(printf '%s' "$_ca_cids" | tr -d ' \t\r\n')" ]; then
        for _mode in config status logs; do
            _ca_siso=$(iso_now_raw); _ca_sep=$(now_epoch)
            _ca_comb="${SCRATCH_DIR}/arc_${_mode}.tmp"; _ca_sub="${SCRATCH_DIR}/arc_sub.tmp"
            : > "$_ca_comb"
            _ca_ok=0; _ca_ne=0; _ca_to=0; _ca_pm=0; _ca_lrc=0
            for _cid in $_ca_cids; do
                case "$_mode" in
                    config) _subs="GETCONFIG ${_cid} AL" ;;
                    status) _subs="GETSTATUS ${_cid}" ;;
                    logs)   _subs="GETLOGS ${_cid} DEAD|GETLOGS ${_cid} DEVICE|GETLOGS ${_cid} EVENT" ;;
                esac
                _oifs="$IFS"; IFS='|'
                for _sc in $_subs; do
                    IFS="$_oifs"
                    : > "$_ca_sub"
                    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_ca_sub" "cd \"${SCRATCH_DIR}\" && \"${_ca_bin}\" ${_sc}"
                    _src=$?; _ca_lrc="$_src"
                    _sst=$(classify_status "$_src" "true" "$_ca_sub")
                    printf '## %s %s\n' "$_ca_dbin" "$_sc" >> "$_ca_comb"
                    cat "$_ca_sub" >> "$_ca_comb"
                    printf '\n' >> "$_ca_comb"
                    case "$_sst" in
                        ok) _ca_ok=1; _ca_ne=1 ;;
                        empty) _ca_ok=1 ;;
                        timeout) _ca_to=1 ;;
                        permission_denied) _ca_pm=1 ;;
                    esac
                    IFS='|'
                done
                IFS="$_oifs"
            done
            _ca_note=""
            if [ "$_ca_to" -eq 1 ]; then _ca_st="timeout"; _ca_lrc=124; _ca_note="subcommand timed out after ${CMD_TIMEOUT_SEC}s"
            elif [ "$_ca_ok" -eq 1 ]; then [ "$_ca_ne" -eq 1 ] && _ca_st="ok" || _ca_st="empty"; _ca_lrc=0
            elif [ "$_ca_pm" -eq 1 ]; then _ca_st="permission_denied"; _ca_note="permission denied (uid=${RUN_AS_UID})"
            else _ca_st="failed"; fi
            case "$_mode" in
                config) _ca_disp="${_ca_dbin} GETCONFIG <N> AL" ;;
                status) _ca_disp="${_ca_dbin} GETSTATUS <N>" ;;
                logs)   _ca_disp="${_ca_dbin} GETLOGS <N> DEAD/DEVICE/EVENT" ;;
            esac
            finalize_item "storage.raid_arcconf_${_mode}" "storage" "storage/raid-arcconf-${_mode}.log" \
                "$_ca_disp" "true" "$_ca_siso" "$_ca_sep" "$_ca_lrc" "$_ca_st" "$CMD_TIMEOUT_SEC" "$_ca_comb" "$_ca_note"
        done
    fi
}

collect_esxi_ssacli() {
    _ss_bin="$1"; _ss_dbin=$(logical_esxi_bin "$_ss_bin")
    run_esxi_raid_cmd "storage.raid_ssacli_status" "storage/raid-ssacli-status.log" "${_ss_dbin} ctrl all show status" "" "ctrl_zero" "\"${_ss_bin}\" ctrl all show status"
    run_esxi_raid_cmd "storage.raid_ssacli_config" "storage/raid-ssacli-config.log" "${_ss_dbin} ctrl all show config detail" "" "ctrl_zero" "\"${_ss_bin}\" ctrl all show config detail"
    run_esxi_raid_cmd "storage.raid_ssacli_detail" "storage/raid-ssacli-detail.log" "${_ss_dbin} ctrl all show detail" "" "ctrl_zero" "\"${_ss_bin}\" ctrl all show detail"
}

collect_esxi_sasircu() {
    _si_tag="$1"; _si_bin="$2"; _si_dbin=$(logical_esxi_bin "$_si_bin")
    _si_siso=$(iso_now_raw); _si_sep=$(now_epoch)
    _si_comb="${SCRATCH_DIR}/${_si_tag}_c.tmp"; _si_sub="${SCRATCH_DIR}/${_si_tag}_s.tmp"
    : > "$_si_comb"; : > "$_si_sub"
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_si_sub" "cd \"${SCRATCH_DIR}\" && \"${_si_bin}\" LIST"
    _si_rc=$?
    _si_st=$(classify_status "$_si_rc" "true" "$_si_sub")
    printf '## %s LIST\n' "$_si_dbin" >> "$_si_comb"
    cat "$_si_sub" >> "$_si_comb"
    printf '\n' >> "$_si_comb"
    _si_cids=""
    if [ "$_si_st" = "ok" ]; then
        _si_cids=$(awk '/^[ \t]+[0-9]+[ \t]+[A-Za-z0-9]/ { if (!seen[$1]++) print $1 }' "$_si_sub" 2>/dev/null | tr '\n' ' ')
        for _cid in $_si_cids; do
            for _subc in DISPLAY STATUS; do
                : > "$_si_sub"
                exec_with_timeout "$CMD_TIMEOUT_SEC" "$_si_sub" "cd \"${SCRATCH_DIR}\" && \"${_si_bin}\" ${_cid} ${_subc}"
                printf '## %s %s %s\n' "$_si_dbin" "$_cid" "$_subc" >> "$_si_comb"
                cat "$_si_sub" >> "$_si_comb"
                printf '\n' >> "$_si_comb"
            done
        done
    fi
    _si_note=""
    if grep -iE 'no lsi sas|no adapters found|no controller' "$_si_comb" >/dev/null 2>&1 && [ -z "$(printf '%s' "$_si_cids" | tr -d ' \t\r\n')" ]; then
        _si_st="not_applicable"; _si_note="no matching SAS controller detected by ${_si_tag}"
    elif [ "$_si_st" = "permission_denied" ]; then _si_note="permission denied (uid=${RUN_AS_UID})"
    elif [ "$_si_st" = "timeout" ]; then _si_note="timed out after ${CMD_TIMEOUT_SEC}s"; fi
    finalize_item "storage.raid_${_si_tag}" "storage" "storage/raid-${_si_tag}.log" \
        "${_si_dbin} LIST; ${_si_dbin} <N> DISPLAY; ${_si_dbin} <N> STATUS" "true" \
        "$_si_siso" "$_si_sep" "$_si_rc" "$_si_st" "$CMD_TIMEOUT_SEC" "$_si_comb" "$_si_note"
}

collect_esxi_raid_detect
_esxi_mega_ran=""
if [ "$RAID_HAS_DELL_PERC" -eq 1 ] && [ -n "$RAID_BIN_PERCCLI" ]; then
    collect_esxi_storcli_family "perccli" "$RAID_BIN_PERCCLI"; _esxi_mega_ran="perccli"
elif [ -n "$RAID_BIN_STORCLI" ]; then
    collect_esxi_storcli_family "storcli" "$RAID_BIN_STORCLI"; _esxi_mega_ran="storcli"
elif [ -n "$RAID_BIN_PERCCLI" ]; then
    collect_esxi_storcli_family "perccli" "$RAID_BIN_PERCCLI"; _esxi_mega_ran="perccli"
elif [ -n "$RAID_BIN_MEGACLI" ]; then
    collect_esxi_megacli "$RAID_BIN_MEGACLI"; _esxi_mega_ran="megacli"
fi
if [ -n "$_esxi_mega_ran" ] && [ "$_esxi_mega_ran" != "megacli" ] && [ -n "$RAID_BIN_MEGACLI" ]; then
    _sa_f="${CFGDIR}/storage/raid-${_esxi_mega_ran}-show-all.log"
    if [ -r "$_sa_f" ] && grep -iE 'number of controllers[ \t]*=[ \t]*0|\[not applicable:' "$_sa_f" >/dev/null 2>&1; then
        collect_esxi_megacli "$RAID_BIN_MEGACLI"
    fi
fi
[ -n "$RAID_BIN_ARCCONF" ]  && collect_esxi_arcconf "$RAID_BIN_ARCCONF"
[ -n "$RAID_BIN_SSACLI" ]   && collect_esxi_ssacli "$RAID_BIN_SSACLI"
[ -n "$RAID_BIN_SAS3IRCU" ] && collect_esxi_sasircu "sas3ircu" "$RAID_BIN_SAS3IRCU"
[ -n "$RAID_BIN_SAS2IRCU" ] && collect_esxi_sasircu "sas2ircu" "$RAID_BIN_SAS2IRCU"
collect_vsan_health

# ── Section 4: network ──
echo "Collecting network information ..."
run_cmd "network.nics" "network" "network/nics.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli network nic list" "esxcli" "esxcli network nic list"
run_multi "network.ip" "network" "network/ip.log" "false" "$CMD_TIMEOUT_SEC" \
    "esxcli network ip interface list; esxcli network ip interface ipv4 get" \
    "esxcli::esxcli network ip interface list" "esxcli::esxcli network ip interface ipv4 get"
run_multi "network.vswitch" "network" "network/vswitch.log" "false" "$CMD_TIMEOUT_SEC" \
    "esxcli network vswitch standard list; esxcli network vswitch dvs vmware list" \
    "esxcli::esxcli network vswitch standard list" "esxcli::esxcli network vswitch dvs vmware list"
run_cmd "network.route" "network" "network/route.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli network ip route ipv4 list" "esxcli" "esxcli network ip route ipv4 list"
run_cmd "network.dns" "network" "network/dns.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli network ip dns server list" "esxcli" "esxcli network ip dns server list"
run_cmd "network.firewall" "network" "network/firewall.log" "false" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli network firewall get" "esxcli" "esxcli network firewall get"
if command -v esxcli >/dev/null 2>&1; then
    for NIC in $(esxcli network nic list 2>/dev/null | awk 'NR>2 && $1 ~ /^[A-Za-z0-9_.-]+$/ {print $1}'); do
        NIC_SAFE=$(sanitize_token "$NIC")
        NIC_ID=$(sanitize_id_part "$NIC")
        run_cmd "network.nic.${NIC_ID}" "network" "network/nic.${NIC_SAFE}.log" "false" "$CMD_TIMEOUT_SEC" "none" \
            "esxcli network nic get -n ${NIC}" "esxcli" "esxcli network nic get -n \"${NIC}\""
    done
fi

# ── Section 5: vms ──
echo "Collecting virtual machine inventory ..."
run_cmd "vms.vm_list" "vms" "vms/vm-list.log" "true" "$CMD_TIMEOUT_SEC" "none" \
    "vim-cmd vmsvc/getallvms" "vim-cmd" "vim-cmd vmsvc/getallvms"
run_cmd "vms.vm_process" "vms" "vms/vm-process.log" "true" "$CMD_TIMEOUT_SEC" "none" \
    "esxcli vm process list" "esxcli" "esxcli vm process list"
collect_vm_snapshots

# ── Section 6: logs ──
echo "Collecting logs (tails) ..."
run_log_tail "logs.vmkernel"   "logs/vmkernel.log"   "/var/log/vmkernel.log"   500
run_log_tail "logs.vmkwarning" "logs/vmkwarning.log" "/var/log/vmkwarning.log" 200
run_log_tail "logs.hostd"      "logs/hostd.log"      "/var/log/hostd.log"      300
run_log_tail "logs.vobd"       "logs/vobd.log"       "/var/log/vobd.log"       200
run_log_tail "logs.syslog"     "logs/syslog.log"     "/var/log/syslog.log"     200

# ── Section 7: performance ──
echo "Collecting performance snapshot ..."
if [ "$SKIP_PERF" = "1" ]; then
    _sp_siso=$(iso_now_raw); _sp_sep=$(now_epoch); : > "${SCRATCH_DIR}/skip.tmp"
    finalize_item "performance.esxtop" "performance" "performance/esxtop.log" \
        "esxtop -b -n 2 -d 5 | head -n 20" "true" "$_sp_siso" "$_sp_sep" -1 "skipped" \
        "$PERF_TIMEOUT_SEC" "${SCRATCH_DIR}/skip.tmp" "skipped via --skip-perf"
else
    run_cmd "performance.esxtop" "performance" "performance/esxtop.log" "true" "$PERF_TIMEOUT_SEC" "head:20" \
        "esxtop -b -n 2 -d 5 | head -n 20" "esxtop" "esxtop -b -n 2 -d 5"
fi
run_cmd "performance.memstats" "performance" "performance/memstats.log" "true" "$CMD_TIMEOUT_SEC" "head:60" \
    "memstats -r comp-stats | head -n 60" "memstats" "memstats -r comp-stats"
run_cmd "performance.psinfo" "performance" "performance/psinfo.log" "false" "$CMD_TIMEOUT_SEC" "head:80" \
    "ps -Tcjstv | head -n 80" "ps" "ps -Tcjstv"

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

FINISH_ISO=$(iso_now_raw)
FINISH_EPOCH=$(now_epoch)
TOTAL_DUR_SEC=$((FINISH_EPOCH - START_EPOCH))
[ "$TOTAL_DUR_SEC" -lt 0 ] && TOTAL_DUR_SEC=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": "vmware-esxi"\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_sec": %s,\n' "$TOTAL_DUR_SEC"
    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 '      "redacted": %s\n' "$CNT_REDACTED"
    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_version": %s,\n' "$(printf '%s' "$OS_VERSION_STR" | 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 '      "shadow_passwd_excluded",\n'
    printf '      "snmp_xml_ssl_key_excluded",\n'
    printf '      "advanced_settings_secret_mask",\n'
    printf '      "log_secret_mask",\n'
    printf '      "streaming_secret_pattern_mask",\n'
    printf '      "raid_safe_id_mask"\n'
    printf '    ]\n'
    printf '  },\n'
    printf '  "warnings": ['
    _wf=1
    while IFS= read -r _wl; do
        [ -n "$_wl" ] || continue
        [ "$_wf" -eq 0 ] && printf ', '
        printf '%s' "$(printf '%s' "$_wl" | json_escape)"
        _wf=0
    done < "$WARNINGS_TXT"
    printf '],\n'
    printf '  "sections": ["system", "hardware", "storage", "network", "vms", "logs", "performance"],\n'
    printf '  "items": [\n'
    _if=1
    while IFS= read -r _il; do
        [ -n "$_il" ] || continue
        [ "$_if" -eq 0 ] && printf ',\n'
        printf '    %s' "$_il"
        _if=0
    done < "$ITEMS_JSONL"
    printf '\n  ]\n'
    printf '}\n'
} > "${CFGDIR}/check.json"

echo "Compressing check data ..."
ARCHIVE_PATH="${BASEDIR%/}/${DIRNAME}.tgz"
rm -f "$ARCHIVE_PATH"
if ( cd "$BASEDIR" && tar -czf "${DIRNAME}.tgz" "${DIRNAME}" ) && [ -s "$ARCHIVE_PATH" ]; then
    rm -rf "$CFGDIR"
    echo "Check data saved to ${ARCHIVE_PATH}"
    exit 0
fi
rm -f "$ARCHIVE_PATH"
echo "ERROR: failed to create archive ${ARCHIVE_PATH}; collected files kept in ${CFGDIR}" >&2
exit 1
