#!/usr/bin/sh
# SPDX-License-Identifier: MIT
# ============================================================
# ITCheckAI OS Check Script - HP-UX
# Version    : 1.2.0
# Schema     : itcheck.hpux.check/1
# Applies to : HP-UX 11i v2 (11.23) / 11i v3 (11.31), PA-RISC and Itanium
# Usage      : sh hpux-check-v1.2.0.sh [output-dir] [--cmd-timeout SEC] [--perf-timeout SEC] [--skip-perf]
# Output     : /var/tmp/<hostname>.<serial>.check-<timestamp>.tar.gz
#              (falls back to .tar.Z when gzip is unavailable)
# Note       : Strictly read-only collection; all ioscan calls use -k (kernel
#              I/O tree cache only, never bus reprobe or driver rebind).
#              Covers HP-UX 11i v3 agile storage/multipath (scsimgr get_attr /
#              lun_map), Fibre Channel HBA status (ioscan -fnkC fc + read-only
#              fcmsutil <dev> & stat only), crashconf -v, ntpq -p, LVM,
#              Serviceguard, logs & performance snapshot.
#              Records raw outputs, per-item execution metadata & lightweight
#              check.json manifest. Never reads /etc/shadow, /etc/passwd,
#              /tcb/files/auth/, SNMP configs or private keys; ps uses 'comm'
#              only (no args), crontab records schedule + executable basename
#              only, and all collected items pass through a streaming 20-class
#              credential redactor.
# ============================================================

umask 077

SCRIPT_NAME="hpux-check"
SCRIPT_VERSION="1.2.0"
SCRIPT_FILE="hpux-check-v1.2.0.sh"
SCHEMA_VERSION="itcheck.hpux.check/1"

LC_ALL=C
LANG=C
export LC_ALL LANG

if [ "${ITCHECK_KEEP_PATH:-0}" != "1" ]; then
    PATH="${PATH}:/usr/sbin:/sbin:/usr/contrib/bin"
    export PATH
fi

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

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

Read-only HP-UX check collector (schema: $SCHEMA_VERSION).

Options:
  [OUTPUT_DIR], --out-dir DIR  Output directory for archive (default: /var/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 vmstat/iostat/sar/top sampling
  --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

[ -z "$OUT_DIR" ] && OUT_DIR="/var/tmp"
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; }

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

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 (HP-UX POSIX sh / ksh + 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 shasum >/dev/null 2>&1; then
        shasum -a 256 "$_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"
}

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 (HP-UX POSIX sh & ksh compatible, reaps sleep 1 child)
exec_with_timeout() {
    _et_sec="$1"
    _et_out="$2"
    _et_cmd="$3"
    _et_flag="${SCRATCH_DIR}/to.$$"
    rm -f "$_et_flag"
    ( trap - 2 15; trap '' 1; eval "$_et_cmd"; exit $? ) </dev/null >"$_et_out" 2>&1 &
    _et_pid=$!
    (
        trap '' 1 2
        _reaped_sl=""
        _sl=""
        trap 'trap "" 15
              if [ -n "$_sl" ] && [ "$_sl" != "$_reaped_sl" ]; then
                  kill -TERM "$_sl" 2>/dev/null
                  wait "$_sl" 2>/dev/null
              fi
              exit 0' 15
        _n=0
        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 '' 15
        : > "$_et_flag"
        for _cp in $(UNIX95= 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 $(UNIX95= 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 awk credential redactor (20 credential classes)
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 }
    {
        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)
        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|can.?t open .*: permission denied' "$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=$(whoami 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 getconf >/dev/null 2>&1; then
    SERIAL_RAW=$(getconf MACHINE_SERIAL 2>/dev/null | head -n 1 | tr -d ' /')
    [ -n "$SERIAL_RAW" ] && SERIAL_SOURCE="getconf"
fi
if [ -z "$SERIAL_RAW" ] && command -v machinfo >/dev/null 2>&1; then
    SERIAL_RAW=$(machinfo 2>/dev/null | grep -i 'machine serial' | head -n 1 | awk -F': *' '{print $2}' | tr -d ' /')
    [ -n "$SERIAL_RAW" ] && SERIAL_SOURCE="machinfo"
fi
SERIAL_FOR_NAME="$SERIAL_RAW"
[ -z "$SERIAL_FOR_NAME" ] && SERIAL_FOR_NAME="NotAvailable"
SERIAL_FOR_NAME=$(sanitize_token "$SERIAL_FOR_NAME")

OS_RELEASE_STR=$(uname -sr 2>/dev/null)
MODEL_STR=$(model 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_hpux_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_hpux_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 0
trap 'cleanup_scratch; exit 130' 1 2 15

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

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

if [ "$IS_ROOT" != "true" ]; then
    NON_ROOT_WARN="WARNING: not running as root (uid=${RUN_AS_UID}), privileged items (lvlnboot/cstm/diskinfo/lanadmin/shutdownlog) may be incomplete."
    printf '%s\n' "$NON_ROOT_WARN" | tee "$CFGDIR/warning.txt"
    add_warning "$NON_ROOT_WARN"
fi

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 [force_red]
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_fred="${4:-false}"

    _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"
        fi
    fi
    [ "$_fi_fred" = "true" ] && _fi_red="true"
    [ "$_fi_red" = "true" ] && CNT_REDACTED=$((CNT_REDACTED + 1))

    _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() {
    _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_fred="${10:-false}"

    _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" "$_rc_fred"
        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
    if [ "$_rc_st" = "ok" ] && [ ! -s "$_rc_out" ]; then
        _rc_st="empty"
    fi

    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" "$_rc_fred"
}

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_mode=""; _slim_n=""
        case "$_sc" in
            *::head:*) _slim_mode="head"; _slim_n="${_sc##*::head:}"; _sc="${_sc%::head:*}" ;;
            *::tail:*) _slim_mode="tail"; _slim_n="${_sc##*::tail:}"; _sc="${_sc%::tail:*}" ;;
        esac
        if [ -n "$_sb" ] && ! command -v "$_sb" >/dev/null 2>&1; then
            continue
        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 [ "$_slim_mode" = "head" ]; then
                head -n "$_slim_n" "$_rm_sub"
            elif [ "$_slim_mode" = "tail" ]; then
                tail -n "$_slim_n" "$_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_file() {
    _rf_id="$1"; _rf_sec="$2"; _rf_rel="$3"; _rf_path="$4"; _rf_req="$5"; _rf_tail="${6:-0}"
    _rf_real="${ROOT_PREFIX}${_rf_path}"
    if [ "$_rf_tail" -gt 0 ]; then
        _rf_disp="tail -n ${_rf_tail} ${_rf_path}"
    else
        _rf_disp="cat ${_rf_path}"
    fi
    _rf_siso=$(iso_now_raw); _rf_sep=$(now_epoch)
    _rf_raw="${SCRATCH_DIR}/file.tmp"; : > "$_rf_raw"

    if [ ! -e "$_rf_real" ]; then
        finalize_item "$_rf_id" "$_rf_sec" "$_rf_rel" "$_rf_disp" "$_rf_req" \
            "$_rf_siso" "$_rf_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_rf_raw" "file not present: $_rf_path"
        return 0
    fi
    if [ ! -r "$_rf_real" ]; then
        finalize_item "$_rf_id" "$_rf_sec" "$_rf_rel" "$_rf_disp" "$_rf_req" \
            "$_rf_siso" "$_rf_sep" 1 "permission_denied" "$CMD_TIMEOUT_SEC" "$_rf_raw" "cannot read $_rf_path (uid=${RUN_AS_UID})"
        return 0
    fi
    if [ "$_rf_tail" -gt 0 ]; then
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_rf_raw" "tail -n ${_rf_tail} \"${_rf_real}\""
    else
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_rf_raw" "cat \"${_rf_real}\""
    fi
    _rf_rc=$?
    _rf_st=$(classify_status "$_rf_rc" "$_rf_req" "$_rf_raw")
    _rf_note=""
    [ "$_rf_st" = "timeout" ] && _rf_note="timed out after ${CMD_TIMEOUT_SEC}s"
    finalize_item "$_rf_id" "$_rf_sec" "$_rf_rel" "$_rf_disp" "$_rf_req" \
        "$_rf_siso" "$_rf_sep" "$_rf_rc" "$_rf_st" "$CMD_TIMEOUT_SEC" "$_rf_raw" "$_rf_note"
}

collect_crontab() {
    _cc_siso=$(iso_now_raw); _cc_sep=$(now_epoch)
    _cc_raw="${SCRATCH_DIR}/cron_raw.tmp"; _cc_out="${SCRATCH_DIR}/cron_out.tmp"
    : > "$_cc_raw"; : > "$_cc_out"
    _cc_rc=0; _cc_state="unavailable"; _cc_st="ok"; _cc_note=""

    if ! command -v crontab >/dev/null 2>&1; then
        _cc_rc=127; _cc_state="command_missing"; _cc_st="command_missing"; _cc_note="command not found: crontab"
    else
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_cc_raw" "crontab -l"
        _cc_rc=$?
        if [ "$_cc_rc" -eq 124 ]; then
            _cc_state="timeout"; _cc_st="timeout"; _cc_note="timed out after ${CMD_TIMEOUT_SEC}s"
        elif [ "$_cc_rc" -eq 0 ]; then
            _cc_state="present"; _cc_st="ok"
        elif grep -iE 'no crontab|can.?t open your crontab' "$_cc_raw" >/dev/null 2>&1; then
            _cc_state="empty"; _cc_rc=0; _cc_st="ok"; : > "$_cc_raw"
        elif is_perm_err_file "$_cc_raw"; then
            _cc_state="permission_denied"; _cc_st="permission_denied"; _cc_note="crontab permission denied (uid=${RUN_AS_UID})"
        else
            _cc_state="failed"; _cc_st="failed"
        fi
    fi

    {
        printf 'crontab_status=%s\n' "$_cc_state"
        if [ "$_cc_state" = "present" ]; then
            awk '
            BEGIN { active = 0; env_cnt = 0; comment_cnt = 0 }
            /^[ \t]*$/ { next }
            /^[ \t]*#/ { comment_cnt++; next }
            /^[ \t]*[A-Za-z_][A-Za-z0-9_]*[ \t]*=/ { env_cnt++; next }
            {
                active++
                n = split($0, f, /[ \t]+/)
                if (substr(f[1], 1, 1) == "@") { sched = f[1]; idx = 2 }
                else if (n >= 6) { sched = f[1] " " f[2] " " f[3] " " f[4] " " f[5]; idx = 6 }
                else { printf "entry=%s [unparsed_line_omitted]\n", f[1]; next }
                while (idx <= n && f[idx] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) idx++
                cmd_tok = (idx <= n) ? f[idx] : "unknown"
                sub(/^.*\//, "", cmd_tok)
                sub(/[=:@?].*$/, "", cmd_tok)
                if (cmd_tok == "") cmd_tok = "command"
                printf "entry=%s %s [args omitted]\n", sched, cmd_tok
            }
            END {
                printf "crontab_active_entries=%d\n", active
                printf "crontab_env_assignments_omitted=%d\n", env_cnt
                printf "crontab_comments_omitted=%d\n", comment_cnt
            }' "$_cc_raw"
        elif [ "$_cc_state" = "empty" ]; then
            printf 'crontab_active_entries=0\ncrontab_env_assignments_omitted=0\ncrontab_comments_omitted=0\n'
        fi
    } > "$_cc_out"

    finalize_item "system.crontab" "system" "system/crontab.log" \
        "crontab -l (schedule & executable basename only; env/comments/args omitted)" "false" \
        "$_cc_siso" "$_cc_sep" "$_cc_rc" "$_cc_st" "$CMD_TIMEOUT_SEC" "$_cc_out" "$_cc_note" "true"
}

collect_bdf_local() {
    # Prefer local-only bdf -l to avoid hanging on unresponsive NFS mounts; fallback to bdf with timeout
    _bd_siso=$(iso_now_raw); _bd_sep=$(now_epoch)
    _bd_raw="${SCRATCH_DIR}/bdf.tmp"; : > "$_bd_raw"
    if ! command -v bdf >/dev/null 2>&1; then
        finalize_item "storage.bdf" "storage" "storage/bdf.log" "bdf -l (fallback bdf)" "false" \
            "$_bd_siso" "$_bd_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_bd_raw" "command not found: bdf"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bd_raw" "bdf -l"
    _bd_rc=$?
    _bd_disp="bdf -l"
    if [ "$_bd_rc" -ne 0 ] && [ "$_bd_rc" -ne 124 ]; then
        : > "$_bd_raw"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_bd_raw" "bdf"
        _bd_rc=$?
        _bd_disp="bdf"
    fi
    _bd_st=$(classify_status "$_bd_rc" "false" "$_bd_raw")
    _bd_note=""
    [ "$_bd_st" = "timeout" ] && _bd_note="timed out after ${CMD_TIMEOUT_SEC}s"
    finalize_item "storage.bdf" "storage" "storage/bdf.log" "$_bd_disp" "false" \
        "$_bd_siso" "$_bd_sep" "$_bd_rc" "$_bd_st" "$CMD_TIMEOUT_SEC" "$_bd_raw" "$_bd_note"
}

collect_pvdisplay() {
    _pv_siso=$(iso_now_raw); _pv_sep=$(now_epoch)
    _pv_out="${SCRATCH_DIR}/pv.tmp"; _pv_sub="${SCRATCH_DIR}/pv_sub.tmp"
    : > "$_pv_out"
    if ! command -v pvdisplay >/dev/null 2>&1 || ! command -v vgdisplay >/dev/null 2>&1; then
        finalize_item "storage.pvdisplay" "storage" "storage/pvdisplay.log" \
            "for PV in vgdisplay -v; do pvdisplay \$PV; done" "true" \
            "$_pv_siso" "$_pv_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_pv_out" "vgdisplay or pvdisplay not found"
        return 0
    fi
    _pv_list=$(awk '/PV Name/ && $3 ~ /^\/dev\/[A-Za-z0-9_\/.-]+$/ && !seen[$3]++ {print $3}' "${CFGDIR}/storage/vgdisplay.log" 2>/dev/null)
    if [ -z "$_pv_list" ]; then
        finalize_item "storage.pvdisplay" "storage" "storage/pvdisplay.log" \
            "for PV in vgdisplay -v; do pvdisplay \$PV; done" "true" \
            "$_pv_siso" "$_pv_sep" 0 "empty" "$CMD_TIMEOUT_SEC" "$_pv_out" "no PV Name entries parsed from vgdisplay"
        return 0
    fi
    _pv_rc=0; _pv_to=0; _pv_perm=0
    for _pv in $_pv_list; do
        : > "$_pv_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_pv_sub" "pvdisplay \"${_pv}\""
        _prc=$?
        printf '## pvdisplay %s\n' "$_pv" >> "$_pv_out"
        cat "$_pv_sub" >> "$_pv_out"
        printf '\n' >> "$_pv_out"
        [ "$_prc" -eq 124 ] && _pv_to=1
        is_perm_err_file "$_pv_sub" && _pv_perm=1
        [ "$_prc" -ne 0 ] && _pv_rc="$_prc"
    done
    _pv_st="ok"; _pv_note=""
    if [ "$_pv_to" -eq 1 ]; then
        _pv_st="timeout"; _pv_rc=124; _pv_note="timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$_pv_rc" -ne 0 ] && [ "$_pv_perm" -eq 1 ]; then
        _pv_st="permission_denied"; _pv_note="requires root privileges (uid=${RUN_AS_UID})"
    elif [ "$_pv_rc" -ne 0 ] && [ ! -s "$_pv_out" ]; then
        _pv_st="failed"
    fi
    finalize_item "storage.pvdisplay" "storage" "storage/pvdisplay.log" \
        "for PV in vgdisplay -v; do pvdisplay \$PV; done" "true" \
        "$_pv_siso" "$_pv_sep" "$_pv_rc" "$_pv_st" "$CMD_TIMEOUT_SEC" "$_pv_out" "$_pv_note"
}

collect_diskinfo() {
    _di_siso=$(iso_now_raw); _di_sep=$(now_epoch)
    _di_out="${SCRATCH_DIR}/diskinfo.tmp"; _di_sub="${SCRATCH_DIR}/di_sub.tmp"
    : > "$_di_out"
    if ! command -v diskinfo >/dev/null 2>&1; then
        finalize_item "storage.diskinfo" "storage" "storage/diskinfo.log" \
            "diskinfo /dev/rdisk/disk* /dev/rdsk/c*t*d0 | head -n 300" "true" \
            "$_di_siso" "$_di_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_di_out" "command not found: diskinfo"
        return 0
    fi
    _di_found=0; _di_to=0; _di_perm=0; _di_rc=0
    for _dsf in "${ROOT_PREFIX}"/dev/rdisk/disk* "${ROOT_PREFIX}"/dev/rdsk/c*t*d0; do
        [ -c "$_dsf" ] || continue
        _di_found=1
        : > "$_di_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_di_sub" "diskinfo \"${_dsf}\""
        _drc=$?
        cat "$_di_sub" >> "$_di_out"
        [ "$_drc" -eq 124 ] && _di_to=1
        is_perm_err_file "$_di_sub" && _di_perm=1
        [ "$_drc" -ne 0 ] && _di_rc="$_drc"
    done
    head -n 300 "$_di_out" > "${SCRATCH_DIR}/di_head.tmp"
    mv "${SCRATCH_DIR}/di_head.tmp" "$_di_out"
    _di_st="ok"; _di_note=""
    if [ "$_di_found" -eq 0 ]; then
        _di_st="not_applicable"; _di_rc=-1; _di_note="no /dev/rdisk/disk* or /dev/rdsk/c*t*d0 character devices present"
    elif [ "$_di_to" -eq 1 ]; then
        _di_st="timeout"; _di_rc=124; _di_note="timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$_di_perm" -eq 1 ] && [ "$_di_rc" -ne 0 ]; then
        _di_st="permission_denied"; _di_note="requires root privileges (uid=${RUN_AS_UID})"
    elif [ ! -s "$_di_out" ]; then
        _di_st="empty"
    fi
    finalize_item "storage.diskinfo" "storage" "storage/diskinfo.log" \
        "diskinfo /dev/rdisk/disk* /dev/rdsk/c*t*d0 | head -n 300" "true" \
        "$_di_siso" "$_di_sep" "$_di_rc" "$_di_st" "$CMD_TIMEOUT_SEC" "$_di_out" "$_di_note"
}

# Read-only Fibre Channel HBA status & statistics from whitelisted devices discovered by 'ioscan -fnkC fc'.
# Strictly runs 'fcmsutil <dev>' and 'fcmsutil <dev> stat' only (never reset/write/clear subcommands).
collect_fcmsutil() {
    _fc_siso=$(iso_now_raw); _fc_sep=$(now_epoch)
    _fc_out="${SCRATCH_DIR}/fcmsutil.tmp"; _fc_sub="${SCRATCH_DIR}/fcmsutil_sub.tmp"
    : > "$_fc_out"
    _fc_disp="for DEV in ioscan -fnkC fc (/dev/fcd*, /dev/td*); do fcmsutil \$DEV; fcmsutil \$DEV stat; done"

    if ! command -v fcmsutil >/dev/null 2>&1; then
        finalize_item "storage.fcmsutil" "storage" "storage/fcmsutil.log" "$_fc_disp" "true" \
            "$_fc_siso" "$_fc_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_fc_out" "command not found: fcmsutil"
        return 0
    fi

    _fc_devs=$(awk '{
        for (i = 1; i <= NF; i++) {
            if ($i ~ /^\/dev\/(fcd|td|fclp|fcoc)[0-9]+$/ && !seen[$i]++) {
                print $i
            }
        }
    }' "${CFGDIR}/hardware/ioscan-fc.log" 2>/dev/null)

    if [ -z "$_fc_devs" ]; then
        finalize_item "storage.fcmsutil" "storage" "storage/fcmsutil.log" "$_fc_disp" "true" \
            "$_fc_siso" "$_fc_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_fc_out" "no /dev/fcd* or /dev/td* FC HBA devices found in ioscan -fnkC fc"
        return 0
    fi

    _fc_rc=0; _fc_ok=0; _fc_to=0; _fc_perm=0; _fc_cnt=0
    for _fcdev in $_fc_devs; do
        case "$_fcdev" in
            /dev/fcd[0-9]*|/dev/td[0-9]*|/dev/fclp[0-9]*|/dev/fcoc[0-9]*) ;;
            *) continue ;;
        esac
        _fc_cnt=$((_fc_cnt + 1))
        if [ "$_fc_cnt" -gt 32 ]; then
            printf '# [capped at 32 FC HBA devices]\n' >> "$_fc_out"
            break
        fi

        : > "$_fc_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_fc_sub" "fcmsutil \"${_fcdev}\""
        _frc1=$?
        printf '## fcmsutil %s\n' "$_fcdev" >> "$_fc_out"
        cat "$_fc_sub" >> "$_fc_out"
        printf '\n' >> "$_fc_out"
        [ "$_frc1" -eq 0 ] && _fc_ok=1
        [ "$_frc1" -eq 124 ] && _fc_to=1
        is_perm_err_file "$_fc_sub" && _fc_perm=1
        [ "$_frc1" -ne 0 ] && _fc_rc="$_frc1"

        : > "$_fc_sub"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_fc_sub" "fcmsutil \"${_fcdev}\" stat"
        _frc2=$?
        printf '## fcmsutil %s stat\n' "$_fcdev" >> "$_fc_out"
        cat "$_fc_sub" >> "$_fc_out"
        printf '\n' >> "$_fc_out"
        [ "$_frc2" -eq 0 ] && _fc_ok=1
        [ "$_frc2" -eq 124 ] && _fc_to=1
        is_perm_err_file "$_fc_sub" && _fc_perm=1
        [ "$_frc2" -ne 0 ] && _fc_rc="$_frc2"
    done

    _fc_st="ok"; _fc_note=""
    if [ "$_fc_to" -eq 1 ]; then
        _fc_st="timeout"; _fc_rc=124; _fc_note="timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$_fc_ok" -eq 1 ]; then
        _fc_st="ok"; _fc_rc=0
    elif [ "$_fc_perm" -eq 1 ]; then
        _fc_st="permission_denied"; _fc_note="requires root privileges (uid=${RUN_AS_UID})"
    else
        _fc_st="failed"
    fi
    finalize_item "storage.fcmsutil" "storage" "storage/fcmsutil.log" "$_fc_disp" "true" \
        "$_fc_siso" "$_fc_sep" "$_fc_rc" "$_fc_st" "$CMD_TIMEOUT_SEC" "$_fc_out" "$_fc_note"
}

collect_netconf() {
    _nc_siso=$(iso_now_raw); _nc_sep=$(now_epoch)
    _nc_out="${SCRATCH_DIR}/netconf.tmp"; : > "$_nc_out"
    _nc_path="${ROOT_PREFIX}/etc/rc.config.d/netconf"
    if [ ! -e "$_nc_path" ]; then
        finalize_item "network.netconf" "network" "network/netconf.log" \
            "grep -v '^#' /etc/rc.config.d/netconf | grep -v '^$'" "false" \
            "$_nc_siso" "$_nc_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_nc_out" "file not present: /etc/rc.config.d/netconf"
        return 0
    fi
    if [ ! -r "$_nc_path" ]; then
        finalize_item "network.netconf" "network" "network/netconf.log" \
            "grep -v '^#' /etc/rc.config.d/netconf | grep -v '^$'" "false" \
            "$_nc_siso" "$_nc_sep" 1 "permission_denied" "$CMD_TIMEOUT_SEC" "$_nc_out" "cannot read /etc/rc.config.d/netconf"
        return 0
    fi
    grep -v '^#' "$_nc_path" 2>/dev/null | grep -v '^$' > "$_nc_out"
    _nc_st="empty"
    [ -s "$_nc_out" ] && _nc_st="ok"
    finalize_item "network.netconf" "network" "network/netconf.log" \
        "grep -v '^#' /etc/rc.config.d/netconf | grep -v '^$'" "false" \
        "$_nc_siso" "$_nc_sep" 0 "$_nc_st" "$CMD_TIMEOUT_SEC" "$_nc_out" ""
}

collect_lan_per_if() {
    _li_kind="$1" # ifconfig | lanadmin
    _li_siso=$(iso_now_raw); _li_sep=$(now_epoch)
    _li_out="${SCRATCH_DIR}/lan_${_li_kind}.tmp"; _li_sub="${SCRATCH_DIR}/lan_sub.tmp"
    : > "$_li_out"
    if [ "$_li_kind" = "ifconfig" ]; then
        _li_id="network.ifconfig"; _li_rel="network/ifconfig.log"; _li_bin="ifconfig"; _li_req="false"
        _li_disp="for LAN in lanscan; do ifconfig \$LAN; done"
        _li_items=$(awk '/lan/ && $5 ~ /^[A-Za-z0-9_:.-]+$/ && !seen[$5]++ {print $5}' "${CFGDIR}/network/lanscan.log" 2>/dev/null)
    else
        _li_id="network.lanadmin"; _li_rel="network/lanadmin.log"; _li_bin="lanadmin"; _li_req="true"
        _li_disp="for PPA in lanscan; do lanadmin -x \$PPA; done"
        _li_items=$(awk '/lan/ && $3 ~ /^[0-9]+$/ && !seen[$3]++ {print $3}' "${CFGDIR}/network/lanscan.log" 2>/dev/null)
    fi
    if ! command -v "$_li_bin" >/dev/null 2>&1; then
        finalize_item "$_li_id" "network" "$_li_rel" "$_li_disp" "$_li_req" \
            "$_li_siso" "$_li_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_li_out" "command not found: $_li_bin"
        return 0
    fi
    if [ -z "$_li_items" ]; then
        finalize_item "$_li_id" "network" "$_li_rel" "$_li_disp" "$_li_req" \
            "$_li_siso" "$_li_sep" 0 "empty" "$CMD_TIMEOUT_SEC" "$_li_out" "no lan entries parsed from lanscan"
        return 0
    fi
    _li_rc=0; _li_to=0; _li_perm=0
    for _tok in $_li_items; do
        : > "$_li_sub"
        if [ "$_li_kind" = "ifconfig" ]; then
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$_li_sub" "ifconfig \"${_tok}\""
            _lrc=$?
            printf '## ifconfig %s\n' "$_tok" >> "$_li_out"
        else
            exec_with_timeout "$CMD_TIMEOUT_SEC" "$_li_sub" "lanadmin -x \"${_tok}\""
            _lrc=$?
            printf '## lanadmin -x %s\n' "$_tok" >> "$_li_out"
        fi
        cat "$_li_sub" >> "$_li_out"
        printf '\n' >> "$_li_out"
        [ "$_lrc" -eq 124 ] && _li_to=1
        is_perm_err_file "$_li_sub" && _li_perm=1
        [ "$_lrc" -ne 0 ] && _li_rc="$_lrc"
    done
    _li_st="ok"; _li_note=""
    if [ "$_li_to" -eq 1 ]; then
        _li_st="timeout"; _li_rc=124; _li_note="timed out after ${CMD_TIMEOUT_SEC}s"
    elif [ "$_li_rc" -ne 0 ] && [ "$_li_perm" -eq 1 ]; then
        _li_st="permission_denied"; _li_note="requires root privileges (uid=${RUN_AS_UID})"
    fi
    finalize_item "$_li_id" "network" "$_li_rel" "$_li_disp" "$_li_req" \
        "$_li_siso" "$_li_sep" "$_li_rc" "$_li_st" "$CMD_TIMEOUT_SEC" "$_li_out" "$_li_note"
}

collect_resolv() {
    _rs_siso=$(iso_now_raw); _rs_sep=$(now_epoch)
    _rs_out="${SCRATCH_DIR}/resolv.tmp"; : > "$_rs_out"
    _rs_found=0
    if [ -r "${ROOT_PREFIX}/etc/resolv.conf" ]; then
        _rs_found=1
        printf '## cat /etc/resolv.conf\n' >> "$_rs_out"
        cat "${ROOT_PREFIX}/etc/resolv.conf" >> "$_rs_out" 2>&1
        printf '\n' >> "$_rs_out"
    fi
    if [ -r "${ROOT_PREFIX}/etc/nsswitch.conf" ]; then
        _rs_found=1
        printf '## grep hosts /etc/nsswitch.conf\n' >> "$_rs_out"
        grep hosts "${ROOT_PREFIX}/etc/nsswitch.conf" >> "$_rs_out" 2>&1
        printf '\n' >> "$_rs_out"
    fi
    if [ "$_rs_found" -eq 0 ]; then
        finalize_item "network.resolv" "network" "network/resolv.log" \
            "cat /etc/resolv.conf; grep hosts /etc/nsswitch.conf" "false" \
            "$_rs_siso" "$_rs_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_rs_out" "files not present"
    else
        finalize_item "network.resolv" "network" "network/resolv.log" \
            "cat /etc/resolv.conf; grep hosts /etc/nsswitch.conf" "false" \
            "$_rs_siso" "$_rs_sep" 0 "ok" "$CMD_TIMEOUT_SEC" "$_rs_out" ""
    fi
}

run_perf_cmd() {
    _rp_id="$1"; _rp_rel="$2"; _rp_disp="$3"; _rp_bin="$4"; _rp_cmd="$5"
    if [ "$SKIP_PERF" = "1" ]; then
        _rp_siso=$(iso_now_raw); _rp_sep=$(now_epoch); : > "${SCRATCH_DIR}/skip.tmp"
        finalize_item "$_rp_id" "performance" "$_rp_rel" "$_rp_disp" "false" \
            "$_rp_siso" "$_rp_sep" -1 "skipped" "$PERF_TIMEOUT_SEC" "${SCRATCH_DIR}/skip.tmp" "skipped via --skip-perf"
        return 0
    fi
    run_cmd "$_rp_id" "performance" "$_rp_rel" "false" "$PERF_TIMEOUT_SEC" "none" "$_rp_disp" "$_rp_bin" "$_rp_cmd"
}

collect_top_snapshot() {
    _tp_siso=$(iso_now_raw); _tp_sep=$(now_epoch)
    _tp_out="${SCRATCH_DIR}/top_out.tmp"; : > "$_tp_out"
    if [ "$SKIP_PERF" = "1" ]; then
        finalize_item "performance.top" "performance" "performance/top.log" \
            "top -d 1 -f performance/top.raw; head -n 40 performance/top.raw" "false" \
            "$_tp_siso" "$_tp_sep" -1 "skipped" "$PERF_TIMEOUT_SEC" "$_tp_out" "skipped via --skip-perf"
        return 0
    fi
    if ! command -v top >/dev/null 2>&1; then
        finalize_item "performance.top" "performance" "performance/top.log" \
            "top -d 1 -f performance/top.raw; head -n 40 performance/top.raw" "false" \
            "$_tp_siso" "$_tp_sep" 127 "command_missing" "$PERF_TIMEOUT_SEC" "$_tp_out" "command not found: top"
        return 0
    fi
    mkdir -p "${CFGDIR}/performance"
    _tp_raw_tmp="${SCRATCH_DIR}/top_raw.tmp"
    rm -f "$_tp_raw_tmp" "${CFGDIR}/performance/top.raw"
    exec_with_timeout "$PERF_TIMEOUT_SEC" "${SCRATCH_DIR}/top_stderr.tmp" "top -d 1 -f \"${_tp_raw_tmp}\""
    _tp_rc=$?
    if [ "$_tp_rc" -eq 124 ]; then
        finalize_item "performance.top" "performance" "performance/top.log" \
            "top -d 1 -f performance/top.raw; head -n 40 performance/top.raw" "false" \
            "$_tp_siso" "$_tp_sep" 124 "timeout" "$PERF_TIMEOUT_SEC" "${SCRATCH_DIR}/top_stderr.tmp" "timed out after ${PERF_TIMEOUT_SEC}s"
        return 0
    fi
    if [ -s "$_tp_raw_tmp" ]; then
        redact_file "$_tp_raw_tmp" "${CFGDIR}/performance/top.raw" "${SCRATCH_DIR}/top_red.flag"
        head -n 40 "${CFGDIR}/performance/top.raw" > "$_tp_out"
        _tp_st="ok"
    elif [ -s "${SCRATCH_DIR}/top_stderr.tmp" ]; then
        head -n 40 "${SCRATCH_DIR}/top_stderr.tmp" > "$_tp_out"
        _tp_st=$(classify_status "$_tp_rc" "false" "${SCRATCH_DIR}/top_stderr.tmp")
    else
        _tp_st=$(classify_status "$_tp_rc" "false" "$_tp_out")
    fi
    finalize_item "performance.top" "performance" "performance/top.log" \
        "top -d 1 -f performance/top.raw; head -n 40 performance/top.raw" "false" \
        "$_tp_siso" "$_tp_sep" "$_tp_rc" "$_tp_st" "$PERF_TIMEOUT_SEC" "$_tp_out" ""
}

collect_ps_top() {
    _pt_id="$1"; _pt_rel="$2"; _pt_col="$3"
    _pt_disp="UNIX95= ps -eo ${_pt_col},pid,user,comm | sort -rn | head -n 11"
    _pt_siso=$(iso_now_raw); _pt_sep=$(now_epoch)
    _pt_raw="${SCRATCH_DIR}/ps_raw.tmp"; _pt_out="${SCRATCH_DIR}/ps_top.tmp"
    : > "$_pt_raw"; : > "$_pt_out"
    if ! command -v ps >/dev/null 2>&1; then
        finalize_item "$_pt_id" "performance" "$_pt_rel" "$_pt_disp" "false" \
            "$_pt_siso" "$_pt_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_pt_out" "command not found: ps" "true"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_pt_raw" "UNIX95= ps -eo ${_pt_col},pid,user,comm"
    _pt_rc=$?
    _pt_st=$(classify_status "$_pt_rc" "false" "$_pt_raw")
    if [ "$_pt_st" = "ok" ]; then
        head -n 1 "$_pt_raw" > "$_pt_out"
        sed '1d' "$_pt_raw" | sort -rn | head -n 10 >> "$_pt_out"
    else
        cp "$_pt_raw" "$_pt_out"
    fi
    finalize_item "$_pt_id" "performance" "$_pt_rel" "$_pt_disp" "false" \
        "$_pt_siso" "$_pt_sep" "$_pt_rc" "$_pt_st" "$CMD_TIMEOUT_SEC" "$_pt_out" "" "true"
}

# ── Section 1: system ──
echo "Collecting system information ..."
run_cmd  "system.uname"    "system" "system/uname.log"    "false" "$CMD_TIMEOUT_SEC" "none" "uname -a" "uname" "uname -a"
run_cmd  "system.machinfo" "system" "system/machinfo.log" "false" "$CMD_TIMEOUT_SEC" "none" "machinfo" "machinfo" "machinfo"
run_multi "system.model"   "system" "system/model.log"    "false" "$CMD_TIMEOUT_SEC" "model; getconf MACHINE_MODEL" \
    "model::model" "getconf::getconf MACHINE_MODEL"
run_multi "system.uptime"  "system" "system/uptime.log"   "false" "$CMD_TIMEOUT_SEC" "uptime; who -b" \
    "uptime::uptime" "who::who -b"
run_cmd  "system.swlist"   "system" "system/swlist.log"   "false" "$CMD_TIMEOUT_SEC" "none" "swlist -l bundle" "swlist" "swlist -l bundle"
run_cmd  "system.swlist_patch" "system" "system/swlist-patch.log" "false" "$CMD_TIMEOUT_SEC" "tail:200" \
    "swlist -l patch | tail -n 200" "swlist" "swlist -l patch"
run_multi "system.kernel_tunables" "system" "system/kernel-tunables.log" "false" "$CMD_TIMEOUT_SEC" \
    "kctune | head -n 200; kmtune | head -n 200" \
    "kctune::kctune::head:200" "kmtune::kmtune::head:200"
collect_crontab
run_cmd  "system.setboot"  "system" "system/setboot.log"  "false" "$CMD_TIMEOUT_SEC" "none" "setboot" "setboot" "setboot"
run_cmd  "system.crashconf" "system" "system/crashconf.log" "true" "$CMD_TIMEOUT_SEC" "none" "crashconf -v" "crashconf" "crashconf -v"
run_cmd  "system.ntp"      "system" "system/ntp.log"      "false" "$CMD_TIMEOUT_SEC" "none" "ntpq -p" "ntpq" "ntpq -p"
run_multi "system.parstatus" "system" "system/parstatus.log" "false" "$CMD_TIMEOUT_SEC" "parstatus; vparstatus" \
    "parstatus::parstatus" "vparstatus::vparstatus"

# ── Section 2: hardware (strictly read-only kernel cache: ioscan -fnk*) ──
echo "Collecting hardware information ..."
run_cmd "hardware.ioscan"      "hardware" "hardware/ioscan.log"      "false" "$CMD_TIMEOUT_SEC" "none" "ioscan -fnk" "ioscan" "ioscan -fnk"
run_cmd "hardware.ioscan_disk" "hardware" "hardware/ioscan-disk.log" "false" "$CMD_TIMEOUT_SEC" "none" "ioscan -fnkC disk" "ioscan" "ioscan -fnkC disk"
run_cmd "hardware.ioscan_fc"   "hardware" "hardware/ioscan-fc.log"   "false" "$CMD_TIMEOUT_SEC" "none" "ioscan -fnkC fc" "ioscan" "ioscan -fnkC fc"
run_multi "hardware.memory"    "hardware" "hardware/memory.log"      "false" "$CMD_TIMEOUT_SEC" \
    "machinfo | grep -i memory; dmesg | grep -i physical" \
    "machinfo::machinfo | grep -i memory" "dmesg::dmesg | grep -i physical"
run_multi "hardware.cpu"       "hardware" "hardware/cpu.log"         "false" "$CMD_TIMEOUT_SEC" \
    "machinfo | grep -i -A2 cpu; ioscan -fnkC processor" \
    "machinfo::machinfo | grep -i -A2 cpu" "ioscan::ioscan -fnkC processor"
run_multi "hardware.fru"       "hardware" "hardware/fru.log"         "true"  "$CMD_TIMEOUT_SEC" \
    "cstm_fru; echo 'selclass qualifier cpu;info;wait;infolog' | cstm | head -n 200" \
    "cstm_fru::cstm_fru" "cstm::echo 'selclass qualifier cpu;info;wait;infolog' | cstm::head:200"
run_cmd "hardware.olrad"       "hardware" "hardware/olrad.log"       "true"  "$CMD_TIMEOUT_SEC" "none" "olrad -q" "olrad" "olrad -q"

# ── Section 3: storage ──
echo "Collecting storage information ..."
run_cmd "storage.vgdisplay" "storage" "storage/vgdisplay.log" "true" "$CMD_TIMEOUT_SEC" "none" "vgdisplay -v" "vgdisplay" "vgdisplay -v"
collect_pvdisplay
run_cmd "storage.lvlnboot"  "storage" "storage/lvlnboot.log"  "true" "$CMD_TIMEOUT_SEC" "none" "lvlnboot -v" "lvlnboot" "lvlnboot -v"
collect_bdf_local
run_cmd "storage.mount"     "storage" "storage/mount.log"     "false" "$CMD_TIMEOUT_SEC" "none" "mount -p" "mount" "mount -p"
run_file "storage.fstab"    "storage" "storage/fstab.log"     "/etc/fstab" "false" 0
run_cmd "storage.swapinfo"  "storage" "storage/swapinfo.log"  "false" "$CMD_TIMEOUT_SEC" "none" "swapinfo -tam" "swapinfo" "swapinfo -tam"
collect_diskinfo
run_multi "storage.scsimgr" "storage" "storage/scsimgr.log" "true" "$CMD_TIMEOUT_SEC" \
    "scsimgr get_attr | head -n 200; scsimgr lun_map | head -n 300" \
    "scsimgr::scsimgr get_attr::head:200" "scsimgr::scsimgr lun_map::head:300"
collect_fcmsutil

# ── Section 4: network ──
echo "Collecting network information ..."
run_cmd "network.lanscan"    "network" "network/lanscan.log"    "false" "$CMD_TIMEOUT_SEC" "none" "lanscan" "lanscan" "lanscan"
collect_netconf
collect_lan_per_if "ifconfig"
run_cmd "network.netstat_in" "network" "network/netstat-in.log" "false" "$CMD_TIMEOUT_SEC" "none" "netstat -in" "netstat" "netstat -in"
run_cmd "network.netstat_rn" "network" "network/netstat-rn.log" "false" "$CMD_TIMEOUT_SEC" "none" "netstat -rn" "netstat" "netstat -rn"
run_cmd "network.netstat_an" "network" "network/netstat-an.log" "false" "$CMD_TIMEOUT_SEC" "head:300" "netstat -an | head -n 300" "netstat" "netstat -an"
collect_resolv
collect_lan_per_if "lanadmin"

# ── Section 5: cluster ──
echo "Collecting cluster information (if any) ..."
run_cmd "cluster.cmviewcl" "cluster" "cluster/cmviewcl.log" "false" "$CMD_TIMEOUT_SEC" "none" "cmviewcl -v" "cmviewcl" "cmviewcl -v"

# ── Section 6: logs ──
echo "Collecting log information ..."
run_file "logs.syslog"      "logs" "logs/syslog.log"      "/var/adm/syslog/syslog.log"    "true" 500
run_file "logs.oldsyslog"   "logs" "logs/oldsyslog.log"   "/var/adm/syslog/OLDsyslog.log" "true" 200
run_cmd  "logs.dmesg"       "logs" "logs/dmesg.log"       "false" "$CMD_TIMEOUT_SEC" "none" "dmesg" "dmesg" "dmesg"
run_file "logs.rc"          "logs" "logs/rc.log"          "/etc/rc.log"                   "false" 100
run_file "logs.shutdownlog" "logs" "logs/shutdownlog.log" "/etc/shutdownlog"              "true" 50

# ── Section 7: performance ──
if [ "$SKIP_PERF" = "1" ]; then
    echo "Collecting performance snapshot (live sampling skipped) ..."
else
    echo "Collecting performance snapshot (about 60 seconds) ..."
fi
run_perf_cmd "performance.vmstat" "performance/vmstat.log" "vmstat 3 10" "vmstat" "vmstat 3 10"
run_perf_cmd "performance.iostat" "performance/iostat.log" "iostat 3 5"  "iostat" "iostat 3 5"
run_perf_cmd "performance.sar"    "performance/sar.log"    "sar 3 5"     "sar"    "sar 3 5"
collect_top_snapshot
collect_ps_top "performance.top10cpu" "performance/top10cpu.log" "pcpu"
collect_ps_top "performance.top10mem" "performance/top10mem.log" "vsz"

# ── Build check.json (itcheck.hpux.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": "hpux"\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_release": %s,\n' "$(printf '%s' "$OS_RELEASE_STR" | json_escape)"
    printf '    "model": %s,\n' "$(printf '%s' "$MODEL_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_tcb_excluded",\n'
    printf '      "snmp_config_private_key_excluded",\n'
    printf '      "ps_comm_only_no_args",\n'
    printf '      "crontab_metadata_only",\n'
    printf '      "streaming_secret_pattern_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", "cluster", "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 ..."
cd "$BASEDIR" || { echo "ERROR: cannot access $BASEDIR; collected files kept in $CFGDIR" >&2; exit 1; }
TAR_PATH="${BASEDIR%/}/${DIRNAME}.tar"
rm -f "$TAR_PATH" "${TAR_PATH}.gz" "${TAR_PATH}.Z"
if tar -cf "$TAR_PATH" "$DIRNAME" && [ -s "$TAR_PATH" ]; then
    :
else
    rm -f "$TAR_PATH"
    echo "ERROR: failed to create tar archive $TAR_PATH; collected files kept in $CFGDIR" >&2
    exit 1
fi
if command -v gzip >/dev/null 2>&1; then
    ARCHIVE_PATH="${TAR_PATH}.gz"
    if gzip -f "$TAR_PATH" && [ -s "$ARCHIVE_PATH" ]; then
        rm -rf "$CFGDIR"
        echo "Check data saved to $ARCHIVE_PATH"
        exit 0
    fi
elif command -v compress >/dev/null 2>&1; then
    ARCHIVE_PATH="${TAR_PATH}.Z"
    if compress -f "$TAR_PATH" && [ -s "$ARCHIVE_PATH" ]; then
        rm -rf "$CFGDIR"
        echo "Check data saved to $ARCHIVE_PATH"
        exit 0
    fi
fi
rm -f "$TAR_PATH" "${TAR_PATH}.gz" "${TAR_PATH}.Z"
echo "ERROR: failed to compress check archive in $BASEDIR; collected files kept in $CFGDIR" >&2
exit 1
