#!/usr/bin/ksh
# SPDX-License-Identifier: MIT
# ============================================================
# ITCheckAI OS Check Script - Oracle Solaris
# Version    : 1.2.0
# Schema     : itcheck.solaris.check/1
# Applies to : Solaris 10 / 11 (SPARC and x86, global zone recommended)
# Usage      : ksh solaris-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; records raw outputs, per-item
#              execution metadata & lightweight check.json manifest.
#              Covers Solaris 11 boot environments (beadm), crash dump config
#              (dumpadm), Fibre Channel HBA ports (fcinfo), ZFS key health
#              properties & capped pool history, FMA, SVM, Zones, SMF & perf.
#              Never reads /etc/shadow, /etc/passwd, SNMP community configs or
#              private keys; ps uses 'comm' only (no args), crontab records
#              schedule + executable basename only, and all items pass through
#              a streaming 20-class credential redactor.
# ============================================================

umask 077

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

LC_ALL=C
LANG=C
export LC_ALL LANG

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

AWK_BIN="awk"
if [ "${ITCHECK_KEEP_PATH:-0}" != "1" ] && [ -x /usr/xpg4/bin/awk ]; then
    AWK_BIN="/usr/xpg4/bin/awk"
elif command -v nawk >/dev/null 2>&1; then
    AWK_BIN="nawk"
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 Oracle Solaris 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/mpstat/sar/prstat 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 (Solaris ksh88/ksh93 + 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 '%s' "${SECONDS%.*}" ;;
        *)
            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_BIN" '{print tolower($1)}'
    elif command -v digest >/dev/null 2>&1; then
        digest -a sha256 "$_cs_f" 2>/dev/null | "$AWK_BIN" '{print tolower($1)}'
    elif command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$_cs_f" 2>/dev/null | "$AWK_BIN" '{print tolower($1)}'
    elif command -v openssl >/dev/null 2>&1; then
        openssl dgst -sha256 "$_cs_f" 2>/dev/null | "$AWK_BIN" '{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_BIN" '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 (ksh88/ksh93 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 $(ps -eo pid,ppid 2>/dev/null | "$AWK_BIN" -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_BIN" -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_BIN" -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 sneep >/dev/null 2>&1; then
    SERIAL_RAW=$(sneep 2>/dev/null | head -n 1 | tr -d ' /')
    [ -n "$SERIAL_RAW" ] && SERIAL_SOURCE="sneep"
fi
if [ -z "$SERIAL_RAW" ] && command -v prtconf >/dev/null 2>&1; then
    SERIAL_RAW=$(prtconf -pv 2>/dev/null | grep -i 'chassis-sn' | head -n 1 | sed "s/.*'\(.*\)'.*/\1/" | tr -d ' /')
    [ -n "$SERIAL_RAW" ] && SERIAL_SOURCE="prtconf"
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=""
if [ -r "${ROOT_PREFIX}/etc/release" ]; then
    OS_RELEASE_STR=$(head -n 1 "${ROOT_PREFIX}/etc/release" 2>/dev/null | sed 's/^[ 	]*//')
fi
KERNEL_REL=$(uname -r 2>/dev/null)
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_solaris_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_solaris_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}), some hardware/FMA/storage/log data will 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" ;;
        grep:*) grep -i "${_rc_flt#grep:}" "$_rc_raw" > "$_rc_out" 2>/dev/null; : ;;
        *) 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_BIN" '
            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_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
}

collect_df_local() {
    # Prefer local-only df (-lh) to avoid hanging on unresponsive NFS mounts; fallback to df -h with timeout
    _df_siso=$(iso_now_raw); _df_sep=$(now_epoch)
    _df_raw="${SCRATCH_DIR}/df.tmp"; : > "$_df_raw"
    if ! command -v df >/dev/null 2>&1; then
        finalize_item "storage.df" "storage" "storage/df.log" "df -lh (fallback df -h)" "false" \
            "$_df_siso" "$_df_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_df_raw" "command not found: df"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_df_raw" "df -lh"
    _df_rc=$?
    _df_disp="df -lh"
    if [ "$_df_rc" -ne 0 ] && [ "$_df_rc" -ne 124 ]; then
        : > "$_df_raw"
        exec_with_timeout "$CMD_TIMEOUT_SEC" "$_df_raw" "df -h"
        _df_rc=$?
        _df_disp="df -h"
    fi
    _df_st=$(classify_status "$_df_rc" "false" "$_df_raw")
    _df_note=""
    [ "$_df_st" = "timeout" ] && _df_note="timed out after ${CMD_TIMEOUT_SEC}s"
    finalize_item "storage.df" "storage" "storage/df.log" "$_df_disp" "false" \
        "$_df_siso" "$_df_sep" "$_df_rc" "$_df_st" "$CMD_TIMEOUT_SEC" "$_df_raw" "$_df_note"
}

# Read-only ZFS key health properties from 'zpool get all' (compatible across Solaris 10 & 11).
collect_zpool_properties() {
    _zp_siso=$(iso_now_raw); _zp_sep=$(now_epoch)
    _zp_raw="${SCRATCH_DIR}/zpool_props_raw.tmp"
    _zp_out="${SCRATCH_DIR}/zpool_props.tmp"
    : > "$_zp_raw"; : > "$_zp_out"
    _zp_disp="zpool get all (key health properties: health/capacity/dedupratio/autoreplace/failmode)"

    if ! command -v zpool >/dev/null 2>&1; then
        finalize_item "storage.zpool_properties" "storage" "storage/zpool-properties.log" "$_zp_disp" "false" \
            "$_zp_siso" "$_zp_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_zp_out" "command not found: zpool"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_zp_raw" "zpool get all"
    _zp_rc=$?
    if [ "$_zp_rc" -eq 124 ]; then
        finalize_item "storage.zpool_properties" "storage" "storage/zpool-properties.log" "$_zp_disp" "false" \
            "$_zp_siso" "$_zp_sep" 124 "timeout" "$CMD_TIMEOUT_SEC" "$_zp_raw" "timed out after ${CMD_TIMEOUT_SEC}s"
        return 0
    fi
    if grep -iE 'no pools available' "$_zp_raw" >/dev/null 2>&1; then
        finalize_item "storage.zpool_properties" "storage" "storage/zpool-properties.log" "$_zp_disp" "false" \
            "$_zp_siso" "$_zp_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_zp_raw" "no ZFS pools available"
        return 0
    fi
    _zp_st=$(classify_status "$_zp_rc" "false" "$_zp_raw")
    _zp_note=""
    [ "$_zp_st" = "permission_denied" ] && _zp_note="permission denied (uid=${RUN_AS_UID})"
    if [ "$_zp_st" = "ok" ]; then
        "$AWK_BIN" '
            NR == 1 && toupper($1) == "NAME" { print; next }
            NF >= 3 {
                p = tolower($2)
                if (p ~ /^(health|capacity|size|alloc|allocated|free|fragmentation|dedupratio|autoreplace|failmode|autoexpand|bootfs|readonly|version|ashift|autotrim)$/) {
                    print
                }
            }' "$_zp_raw" > "$_zp_out" 2>/dev/null
        if [ ! -s "$_zp_out" ]; then
            head -n 60 "$_zp_raw" > "$_zp_out"
        fi
    else
        cp "$_zp_raw" "$_zp_out"
    fi
    finalize_item "storage.zpool_properties" "storage" "storage/zpool-properties.log" "$_zp_disp" "false" \
        "$_zp_siso" "$_zp_sep" "$_zp_rc" "$_zp_st" "$CMD_TIMEOUT_SEC" "$_zp_out" "$_zp_note"
}

# Read-only ZFS pool history tail (capped at 80 lines + recent scrub entries, masks encryption keylocation/keysource).
collect_zpool_history() {
    _zh_siso=$(iso_now_raw); _zh_sep=$(now_epoch)
    _zh_raw="${SCRATCH_DIR}/zpool_hist_raw.tmp"
    _zh_cln="${SCRATCH_DIR}/zpool_hist_cln.tmp"
    _zh_out="${SCRATCH_DIR}/zpool_hist.tmp"
    _zh_flg="${SCRATCH_DIR}/zpool_hist_red.flag"
    : > "$_zh_raw"; : > "$_zh_cln"; : > "$_zh_out"
    printf '0\n' > "$_zh_flg"
    _zh_disp="zpool history | tail -n 80 (plus recent scrub events; sensitive options masked)"

    if ! command -v zpool >/dev/null 2>&1; then
        finalize_item "storage.zpool_history" "storage" "storage/zpool-history.log" "$_zh_disp" "false" \
            "$_zh_siso" "$_zh_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_zh_out" "command not found: zpool"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_zh_raw" "zpool history"
    _zh_rc=$?
    if [ "$_zh_rc" -eq 124 ]; then
        finalize_item "storage.zpool_history" "storage" "storage/zpool-history.log" "$_zh_disp" "false" \
            "$_zh_siso" "$_zh_sep" 124 "timeout" "$CMD_TIMEOUT_SEC" "$_zh_raw" "timed out after ${CMD_TIMEOUT_SEC}s"
        return 0
    fi
    if grep -iE 'no pools available' "$_zh_raw" >/dev/null 2>&1; then
        finalize_item "storage.zpool_history" "storage" "storage/zpool-history.log" "$_zh_disp" "false" \
            "$_zh_siso" "$_zh_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_zh_raw" "no ZFS pools available"
        return 0
    fi
    _zh_st=$(classify_status "$_zh_rc" "false" "$_zh_raw")
    _zh_note=""
    _zh_fred="false"
    [ "$_zh_st" = "permission_denied" ] && _zh_note="permission denied (uid=${RUN_AS_UID})"
    if [ "$_zh_st" = "ok" ]; then
        # Mask ZFS encryption key paths/sources (keylocation/keysource) so off-path secrets are never exposed
        "$AWK_BIN" -v flg="$_zh_flg" '
        BEGIN { chg = 0 }
        {
            s = $0
            out = ""; rest = s
            while (match(tolower(rest), /(keylocation|keysource|keyfile|encryptionroot|wrappingkey)[ \t]*=[ \t]*/)) {
                head = substr(rest, 1, RSTART + RLENGTH - 1)
                tail = substr(rest, RSTART + RLENGTH)
                if (match(tail, /^[^ \t"'\'';,]+/)) {
                    val = substr(tail, 1, RLENGTH)
                    if (tolower(val) != "prompt" && tolower(val) != "none" && tolower(val) != "[redacted]") {
                        out = out head "[REDACTED]"
                        rest = substr(tail, RLENGTH + 1)
                        chg = 1
                        continue
                    }
                }
                out = out head; rest = tail
            }
            print out rest
        }
        END { printf "%d\n", chg > flg }' "$_zh_raw" > "$_zh_cln"
        [ "$(cat "$_zh_flg" 2>/dev/null)" = "1" ] && _zh_fred="true"
        {
            _scrub_tmp="${SCRATCH_DIR}/zpool_scrub.tmp"
            grep -i 'scrub' "$_zh_cln" 2>/dev/null | tail -n 10 > "$_scrub_tmp"
            if [ -s "$_scrub_tmp" ]; then
                printf '## recent scrub events (last 10)\n'
                cat "$_scrub_tmp"
                printf '\n'
            fi
            printf '## zpool history (last 80 lines)\n'
            tail -n 80 "$_zh_cln"
        } > "$_zh_out"
    else
        cp "$_zh_raw" "$_zh_out"
    fi
    finalize_item "storage.zpool_history" "storage" "storage/zpool-history.log" "$_zh_disp" "false" \
        "$_zh_siso" "$_zh_sep" "$_zh_rc" "$_zh_st" "$CMD_TIMEOUT_SEC" "$_zh_out" "$_zh_note" "$_zh_fred"
}

# Read-only Fibre Channel HBA port & link status (marks not_applicable when host has no FC HBA).
collect_fcinfo() {
    _fc_siso=$(iso_now_raw); _fc_sep=$(now_epoch)
    _fc_raw="${SCRATCH_DIR}/fcinfo_raw.tmp"
    : > "$_fc_raw"
    _fc_disp="fcinfo hba-port"

    if ! command -v fcinfo >/dev/null 2>&1; then
        finalize_item "storage.fcinfo" "storage" "storage/fcinfo.log" "$_fc_disp" "true" \
            "$_fc_siso" "$_fc_sep" 127 "command_missing" "$CMD_TIMEOUT_SEC" "$_fc_raw" "command not found: fcinfo"
        return 0
    fi
    exec_with_timeout "$CMD_TIMEOUT_SEC" "$_fc_raw" "fcinfo hba-port"
    _fc_rc=$?
    if [ "$_fc_rc" -eq 124 ]; then
        finalize_item "storage.fcinfo" "storage" "storage/fcinfo.log" "$_fc_disp" "true" \
            "$_fc_siso" "$_fc_sep" 124 "timeout" "$CMD_TIMEOUT_SEC" "$_fc_raw" "timed out after ${CMD_TIMEOUT_SEC}s"
        return 0
    fi
    if ! is_perm_err_file "$_fc_raw" && grep -iE 'no adapters found|no hba ports found|no fibre channel' "$_fc_raw" >/dev/null 2>&1; then
        finalize_item "storage.fcinfo" "storage" "storage/fcinfo.log" "$_fc_disp" "true" \
            "$_fc_siso" "$_fc_sep" -1 "not_applicable" "$CMD_TIMEOUT_SEC" "$_fc_raw" "no Fibre Channel HBA ports found"
        return 0
    fi
    _fc_st=$(classify_status "$_fc_rc" "true" "$_fc_raw")
    _fc_note=""
    [ "$_fc_st" = "permission_denied" ] && _fc_note="permission denied (uid=${RUN_AS_UID})"
    finalize_item "storage.fcinfo" "storage" "storage/fcinfo.log" "$_fc_disp" "true" \
        "$_fc_siso" "$_fc_sep" "$_fc_rc" "$_fc_st" "$CMD_TIMEOUT_SEC" "$_fc_raw" "$_fc_note"
}

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_ps_top() {
    _pt_id="$1"; _pt_rel="$2"; _pt_col="$3"
    _pt_disp="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" "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_file "system.release" "system" "system/release.log" "/etc/release" "false" 0
run_cmd  "system.uname"   "system" "system/uname.log"   "false" "$CMD_TIMEOUT_SEC" "none" "uname -a" "uname" "uname -a"
run_cmd  "system.isainfo" "system" "system/isainfo.log" "false" "$CMD_TIMEOUT_SEC" "none" "isainfo -v" "isainfo" "isainfo -v"
run_multi "system.uptime" "system" "system/uptime.log"  "false" "$CMD_TIMEOUT_SEC" "uptime; who -b" "uptime::uptime" "who::who -b"
run_cmd  "system.eeprom"  "system" "system/eeprom.log"  "true"  "$CMD_TIMEOUT_SEC" "none" "eeprom" "eeprom" "eeprom"
run_cmd  "system.beadm"   "system" "system/beadm.log"   "false" "$CMD_TIMEOUT_SEC" "none" "beadm list" "beadm" "beadm list"
run_cmd  "system.dumpadm" "system" "system/dumpadm.log" "false" "$CMD_TIMEOUT_SEC" "none" "dumpadm" "dumpadm" "dumpadm"
collect_crontab
run_cmd  "system.zones"   "system" "system/zones.log"   "false" "$CMD_TIMEOUT_SEC" "none" "zoneadm list -cv" "zoneadm" "zoneadm list -cv"
run_multi "system.patches" "system" "system/patches.log" "false" "$CMD_TIMEOUT_SEC" \
    "showrev -p | tail -n 100; pkg list | head -n 200" \
    "showrev::showrev -p::tail:100" "pkg::pkg list::head:200"

# ── Section 2: hardware ──
echo "Collecting hardware information ..."
run_cmd "hardware.prtconf" "hardware" "hardware/prtconf.log" "false" "$CMD_TIMEOUT_SEC" "head:800" "prtconf -v | head -n 800" "prtconf" "prtconf -v"
run_cmd "hardware.prtdiag" "hardware" "hardware/prtdiag.log" "false" "$CMD_TIMEOUT_SEC" "none" "prtdiag -v" "prtdiag" "prtdiag -v"
run_multi "hardware.psrinfo" "hardware" "hardware/psrinfo.log" "false" "$CMD_TIMEOUT_SEC" "psrinfo -v; psrinfo -pv" \
    "psrinfo::psrinfo -v" "psrinfo::psrinfo -pv"
run_cmd "hardware.memory" "hardware" "hardware/memory.log" "false" "$CMD_TIMEOUT_SEC" "grep:memory" "prtconf | grep -i memory" "prtconf" "prtconf"
run_cmd "hardware.cfgadm" "hardware" "hardware/cfgadm.log" "true"  "$CMD_TIMEOUT_SEC" "none" "cfgadm -al" "cfgadm" "cfgadm -al"
run_cmd "hardware.fmadm"  "hardware" "hardware/fmadm.log"  "true"  "$CMD_TIMEOUT_SEC" "none" "fmadm faulty -a" "fmadm" "fmadm faulty -a"
run_cmd "hardware.fmdump" "hardware" "hardware/fmdump.log" "true"  "$CMD_TIMEOUT_SEC" "tail:100" "fmdump | tail -n 100" "fmdump" "fmdump"
run_cmd "hardware.ipmitool" "hardware" "hardware/ipmitool.log" "true" "$CMD_TIMEOUT_SEC" "tail:100" "ipmitool sel elist | tail -n 100" "ipmitool" "ipmitool sel elist"

# ── Section 3: storage ──
echo "Collecting storage information ..."
run_cmd "storage.format" "storage" "storage/format.log" "true" "$CMD_TIMEOUT_SEC" "none" "printf '\\n' | format" "format" "printf '\\n' | format"
run_cmd "storage.iostat_e" "storage" "storage/iostat-e.log" "false" "$CMD_TIMEOUT_SEC" "none" "iostat -En" "iostat" "iostat -En"
run_cmd "storage.zpool_status" "storage" "storage/zpool-status.log" "false" "$CMD_TIMEOUT_SEC" "none" "zpool status -v" "zpool" "zpool status -v"
run_multi "storage.zpool_list" "storage" "storage/zpool-list.log" "false" "$CMD_TIMEOUT_SEC" "zpool list; zfs list" \
    "zpool::zpool list" "zfs::zfs list"
collect_zpool_properties
collect_zpool_history
run_multi "storage.metastat" "storage" "storage/metastat.log" "false" "$CMD_TIMEOUT_SEC" "metastat -c; metastat | head -n 200" \
    "metastat::metastat -c" "metastat::metastat::head:200"
collect_df_local
run_cmd "storage.mount" "storage" "storage/mount.log" "false" "$CMD_TIMEOUT_SEC" "none" "mount -p" "mount" "mount -p"
run_file "storage.vfstab" "storage" "storage/vfstab.log" "/etc/vfstab" "false" 0
run_multi "storage.swap" "storage" "storage/swap.log" "false" "$CMD_TIMEOUT_SEC" "swap -l; swap -s" "swap::swap -l" "swap::swap -s"
run_cmd "storage.mpathadm" "storage" "storage/mpathadm.log" "true" "$CMD_TIMEOUT_SEC" "none" "mpathadm list lu" "mpathadm" "mpathadm list lu"
collect_fcinfo
run_cmd "storage.vxdisk" "storage" "storage/vxdisk.log" "true" "$CMD_TIMEOUT_SEC" "none" "vxdisk -o alldgs list" "vxdisk" "vxdisk -o alldgs list"

# ── Section 4: network ──
echo "Collecting network information ..."
run_cmd "network.ifconfig" "network" "network/ifconfig.log" "false" "$CMD_TIMEOUT_SEC" "none" "ifconfig -a" "ifconfig" "ifconfig -a"
run_multi "network.dladm" "network" "network/dladm.log" "false" "$CMD_TIMEOUT_SEC" \
    "dladm show-phys; dladm show-link; dladm show-aggr" \
    "dladm::dladm show-phys" "dladm::dladm show-link" "dladm::dladm show-aggr"
run_cmd "network.ipadm" "network" "network/ipadm.log" "false" "$CMD_TIMEOUT_SEC" "none" "ipadm show-addr" "ipadm" "ipadm show-addr"
run_cmd "network.netstat_rn" "network" "network/netstat-rn.log" "false" "$CMD_TIMEOUT_SEC" "none" "netstat -rn" "netstat" "netstat -rn"
run_cmd "network.netstat_in" "network" "network/netstat-in.log" "false" "$CMD_TIMEOUT_SEC" "none" "netstat -in" "netstat" "netstat -in"
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

# ── Section 5: services & logs ──
echo "Collecting service and log information ..."
run_cmd "services.svcs_failed" "services" "services/svcs-failed.log" "false" "$CMD_TIMEOUT_SEC" "none" "svcs -xv" "svcs" "svcs -xv"
run_cmd "services.svcs_all" "services" "services/svcs-all.log" "false" "$CMD_TIMEOUT_SEC" "head:300" "svcs -a | head -n 300" "svcs" "svcs -a"
run_file "logs.messages" "logs" "logs/messages.log" "/var/adm/messages" "true" 500
run_file "logs.sulog"    "logs" "logs/sulog.log"    "/var/adm/sulog"    "true" 100
run_cmd  "logs.dmesg"    "logs" "logs/dmesg.log"    "false" "$CMD_TIMEOUT_SEC" "tail:300" "dmesg | tail -n 300" "dmesg" "dmesg"

# ── Section 6: 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 -xnz 3 5" "iostat" "iostat -xnz 3 5"
run_perf_cmd "performance.mpstat" "performance/mpstat.log" "mpstat 3 3"     "mpstat" "mpstat 3 3"
run_perf_cmd "performance.sar"    "performance/sar.log"    "sar 3 5"        "sar"    "sar 3 5"
run_perf_cmd "performance.prstat" "performance/prstat.log" "prstat -n 15 3 2" "prstat" "prstat -n 15 3 2"
collect_ps_top "performance.top10cpu" "performance/top10cpu.log" "pcpu"
collect_ps_top "performance.top10mem" "performance/top10mem.log" "pmem"

# ── Build check.json (itcheck.solaris.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": "solaris"\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 '    "kernel": %s,\n' "$(printf '%s' "$KERNEL_REL" | json_escape)"
    printf '    "arch": %s\n' "$(printf '%s' "$ARCH_STR" | json_escape)"
    printf '  },\n'
    printf '  "redaction": {\n'
    printf '    "applied": true,\n'
    printf '    "mode": "collector_default",\n'
    printf '    "rules": [\n'
    printf '      "shadow_passwd_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", "services", "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
