#!/usr/bin/ksh
#==============================================================================
#  aix-check-v1.8.0.sh  -  AIX / VIOS Health Check Collector (Single Log Output)
#------------------------------------------------------------------------------
#  Version : 1.8.0
#  Schema  : itcheck.aix.check/1
#  Purpose : Run standard AIX / VIOS check commands sequentially and save
#            prompts, redacted outputs, per-item exit status, and an embedded
#            lightweight check manifest into a single .log text file.
#            Read-only, no .tar.gz archiving, no multi-file splitting.
#  Safety  : Strictly read-only (query / display forms of commands only);
#            no raw disk reads; entstat only on EtherChannel adapters (no -d,
#            never -r); fcstat only on FC ports with a live link (lspath /
#            lsnports / Available tape or non-MPIO disk under an fscsi with
#            attach!=none and a fabric scsi_id, 30s timeout);
#            df checks only local jfs/jfs2 (skips NFS to avoid kernel hangs)
#            and -o rejects network file systems; lsvg/lslv use -L so they
#            never wait for a VG lock; per-command timeout kills the command
#            process tree (TERM -> KILL, only PIDs whose parent link or PGID
#            still matches); the watchdog reaps its own 'sleep 1' child (no
#            orphan sleep / defunct left in normal runs); child processes can
#            never run the main shell's signal / EXIT traps; circuit breaker:
#            3 timeouts in a row skip the rest of a section, 8 timeouts in
#            total or the -T deadline skip the rest of the run; no pathname
#            expansion (set -f), cwd is "/", and every name taken from command
#            output (hdisk / VG / adapter / mount point) is whitelist-checked;
#            pre-checks free disk space and stops collecting when the output
#            file system drops below 150 MB free (checked at every section
#            start and after 'errpt -a'); errpt -a defaults to last 100 days;
#            when that window cannot be used (clock out of range, -s rejected
#            while the error log has entries in the window) the automatic
#            fallback 'errpt -a' is capped at 200000 lines (-d 0 = uncapped);
#            umask 077 ensures log file is readable only by the running user;
#            credential boundary: never reads /etc/security/passwd, shadow,
#            SNMP community configs or private keys; process tables collect
#            command basenames (comm) without raw command-line args; crontab
#            emits schedule + executable basename only; all logged command
#            outputs pass through a POSIX awk streaming credential redactor.
#  Log     : "[YYYY-MM-DD HH:MM:SS] user@host:/> command" prompt, redacted
#            output, then "#@ rc=N sec=N status=STATE redacted=0|1"
#            (rc 124 = timeout, 125 = skipped, 127 = command_missing; rc 1 of
#            a "... | grep" filter only means "no match"). Lines starting with
#            "*** TIMEOUT", "*** SKIPPED" or "*** SKIP" mark missing data;
#            "*** NOTE" lines explain a changed or reduced form of a check.
#            An embedded JSON manifest (itcheck.aix.check/1) is appended
#            in the log trailer for machine-readable auditing.
#  Usage   :
#    1) Standalone on AIX/VIOS (root recommended; on VIOS run 'oem_setup_env'):
#         ksh aix-check-v1.8.0.sh                        # -> /tmp/healthcheck/<host>_<time>.log
#         ksh aix-check-v1.8.0.sh -o /tmp/healthcheck    # absolute output dir or .log file path
#         ksh aix-check-v1.8.0.sh -A                     # full 'lsattr -El' on every hdisk
#         ksh aix-check-v1.8.0.sh -d 0                   # full 'errpt -a' history
#         ksh aix-check-v1.8.0.sh -T 0                   # no whole-run deadline
#         ksh aix-check-v1.8.0.sh -V                     # print version and schema
#    2) Stdout mode (for remote SSH collection, also saves to /tmp/healthcheck):
#         ksh aix-check-v1.8.0.sh -s
#  Exit    : 0 success; 3 completed, but some commands timed out or were
#            skipped (marked *** TIMEOUT / *** SKIPPED), with -E also when a
#            core command returned non-zero (ERROR_COUNT); 2 argument/environment
#            error; 130 interrupted by signal
#  History : 1.8.0  targeted enterprise AIX / VIOS gap closure (IBM PIQS & FLRTVC):
#                   - adds 'no -a' (PIQS network baseline), 'ioo -a', and
#                     'schedo -a' with explicit per-command timeouts;
#                   - adds read-only 'lsattr -El' on Available Virtual I/O
#                     Ethernet adapters (ent*, whitelisted, capped at 32) to
#                     cover mtu_bypass and min_buf_*/max_buf_* without running
#                     entstat -d/-r on non-EtherChannel adapters;
#                   - adds 'ulimit -a' and redacted resource-limit stanzas from
#                     /etc/security/limits (never touches /etc/security/passwd);
#                   - aligns FLRTVC vulnerability inventory with 'lslpp -Lqc'
#                     and 'emgr -lv3' (auto-falling back to 'emgr -l' only if
#                     -lv3 is rejected by an older emgr build);
#                   - on VIOS, adds strictly read-only 'vioshc' status check
#                     (marks command_missing when unavailable).
#            1.7.0  align with ITCheckAI lightweight check manifest
#                   (schema itcheck.aix.check/1) while preserving all
#                   1.6.6 production safeguards (process-tree watchdog, circuit
#                   breaker, lsvg -L lock-free queries, local jfs/jfs2 df,
#                   disk-space guard, exit-code contract):
#                   - records raw timezone timestamps (START_TIME_RAW,
#                     TIMEZONE, DATE_RAW, FINISHED_AT_RAW) without fabricating
#                     timezone suffixes;
#                   - supports non-root degraded execution with explicit
#                     RUN_AS_USER / RUN_AS_UID / IS_ROOT / PRIVILEGE_MODE
#                     metadata, directory ownership guard matching the active
#                     user, and per-item permission_denied / command_missing
#                     classification;
#                   - hardens 20 credential redaction boundaries: process
#                     queries use 'comm' only (no raw args), crontab records
#                     schedule + executable basename only (env/comments/args
#                     omitted), and every logged output passes through a
#                     streaming POSIX awk redactor covering PEM keys, shadow /
#                     AIX passwd hashes, URLs, Auth/Cookie/API-key headers,
#                     Bearer/JWT/cloud tokens, SNMP communities, SQL/DB env,
#                     CLI flags, mount/iSCSI secrets, and sensitive KV/lsattr;
#                   - emits "#@ rc=N sec=N status=STATE redacted=0|1" per item
#                     and appends an embedded JSON manifest block at log end;
#                   - adds -V (--version equivalent) and header-aware free_mb.
#            1.6.6  child-trap isolation (_IN_MAIN=0), watchdog sleep reaping,
#                   PGID-verified kill_tree, capped errpt fallback, -E option.
#==============================================================================

SCRIPT_NAME="aix-check"
VERSION="1.8.0"
SCRIPT_FILE="aix-check-v1.8.0.sh"
SCHEMA_VERSION="itcheck.aix.check/1"
BASEDIR="${ITCHECK_OUT_DIR:-/tmp/healthcheck}"
OUTFILE=""
STDOUT_MODE=0
ALL_DISKS=0
ERR_EXIT=0              # -E: exit 3 also when core commands returned non-zero
CMD_TIMEOUT="${ITCHECK_CMD_TIMEOUT:-120}"
GLOBAL_TIMEOUT="${ITCHECK_GLOBAL_TIMEOUT:-1800}"   # -T: whole-run deadline in seconds, 0 = unlimited
ERRPT_DAYS=100          # errpt -a covers last N days (1 quarter), 0 = full history
ERRPT_MAX_LINES=200000  # line cap of the automatic (not -d 0) full 'errpt -a' fallback
MIN_FREE_MB="${ITCHECK_MIN_FREE_MB:-300}"          # minimum free space (MB) required in output directory
MIN_KEEP_MB="${ITCHECK_MIN_KEEP_MB:-150}"          # free space (MB) below which the rest of the run is skipped
MAX_TO_STREAK=3         # consecutive timeouts in one section -> skip the rest of that section
MAX_TO_TOTAL=8          # timeouts in the whole run -> skip everything left
ROOT_PREFIX="${ITCHECK_ROOT:-}"
LOG=""                  # set once the log file path is known (on_signal checks it)

usage() {
  cat <<EOF
$SCRIPT_FILE $VERSION (schema: $SCHEMA_VERSION) - AIX / VIOS check collector (single log output)
Usage: ksh $SCRIPT_FILE [options]
  -o PATH   output directory, or log file path if PATH ends with .log; must be absolute
            and on a local file system (default: /tmp/healthcheck/<host>_<time>.log)
            the directory must be owned by the running user and not group/other writable
  -s        also print full log to stdout (used by aix_batch.sh over SSH)
  -A        run full 'lsattr -El' on every hdisk (default with >10 disks: summary table
            of all disks + full 'lsattr -El' of the first rootvg disk and one disk per PCM)
  -t SEC    per-command timeout in seconds (default: $CMD_TIMEOUT); long-running commands
            (fixed timeout >= 120s) always get at least SEC
  -T SEC    whole-run deadline in seconds, 0 = unlimited (default: $GLOBAL_TIMEOUT);
            commands not yet started at the deadline are skipped
  -d DAYS   'errpt -a' covers the last DAYS days, 0 = whole error log (default: $ERRPT_DAYS);
            if the window cannot be used, the automatic full 'errpt -a' is capped at
            $ERRPT_MAX_LINES lines (only -d 0 gives the uncapped full history)
  -E        exit 3 also when a core command returned non-zero (ERROR_COUNT > 0)
  -V        print version and schema identifier, then exit
  -h        show this help
Exit: 0 done; 3 done with warnings (some commands timed out or were skipped: circuit
      breaker $MAX_TO_STREAK timeouts in a row skip the rest of a section; $MAX_TO_TOTAL in total,
      the -T deadline or less than $MIN_KEEP_MB MB free skip the rest of the run; with -E
      also core command errors); 2 usage/environment error; 130 interrupted
EOF
}

if [ "${1:-}" = "--version" ]; then
  printf '%s %s (schema: %s)\n' "$SCRIPT_NAME" "$VERSION" "$SCHEMA_VERSION"
  exit 0
fi
if [ "${1:-}" = "--help" ]; then
  usage
  exit 0
fi

while getopts "o:sAt:d:T:EVh" OPT; do
  case $OPT in
    o) OUTFILE=$OPTARG ;;
    s) STDOUT_MODE=1 ;;
    A) ALL_DISKS=1 ;;
    t) CMD_TIMEOUT=$OPTARG ;;
    d) ERRPT_DAYS=$OPTARG ;;
    T) GLOBAL_TIMEOUT=$OPTARG ;;
    E) ERR_EXIT=1 ;;
    V) printf '%s %s (schema: %s)\n' "$SCRIPT_NAME" "$VERSION" "$SCHEMA_VERSION"; exit 0 ;;
    h) usage; exit 0 ;;
    *) usage; exit 2 ;;
  esac
done

# -t must be a positive integer, -T / -d must be non-negative integers, -o must be absolute
is_uint() {
  case $1 in ''|*[!0-9]*) return 1 ;; esac
  return 0
}
if is_uint "$CMD_TIMEOUT" && [ "$CMD_TIMEOUT" -gt 0 ]; then :; else
  echo "ERROR: -t needs a positive integer (seconds)" >&2
  exit 2
fi
if is_uint "$GLOBAL_TIMEOUT"; then :; else
  echo "ERROR: -T needs a non-negative integer (seconds)" >&2
  exit 2
fi
if is_uint "$ERRPT_DAYS"; then :; else
  echo "ERROR: -d needs a non-negative integer (days)" >&2
  exit 2
fi
case $OUTFILE in
  ""|/*) ;;
  *) echo "ERROR: -o needs an absolute path (e.g. -o /tmp/healthcheck)" >&2; exit 2 ;;
esac

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

#------------------------------ Environment Init ------------------------------
# Use C locale for stable command output without altering host timezone (TZ).
LANG=C; LC_ALL=C; export LANG LC_ALL
if [ "${ITCHECK_KEEP_PATH:-0}" != "1" ]; then
  PATH=/usr/bin:/usr/sbin:/etc:/sbin:/usr/ucb:/usr/es/sbin/cluster/utilities:/usr/es/sbin/cluster:/usr/ios/cli:/usr/ios/utils:/usr/DynamicLinkManager/bin:/opt/freeware/bin
  export PATH
fi
umask 077               # Restrict log permissions to the running user only
set -f                  # No pathname expansion: command output can never turn into file names
cd / || exit 2          # Fixed cwd: never a hung NFS directory or one holding crafted file names

if [ "$(uname -s 2>/dev/null)" != "AIX" ]; then
  echo "ERROR: this script must be run on AIX / VIOS." >&2
  exit 2
fi

RUN_AS_UID=$(id -u 2>/dev/null)
is_uint "$RUN_AS_UID" || RUN_AS_UID=65534
RUN_AS_USER=$(id -un 2>/dev/null)
[ -n "$RUN_AS_USER" ] || RUN_AS_USER=$(whoami 2>/dev/null)
[ -n "$RUN_AS_USER" ] || RUN_AS_USER="unknown"
PRIV_WARN=""
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"
  PRIV_WARN="not running as root (uid=$RUN_AS_UID, user=$RUN_AS_USER); privileged checks may report permission_denied (on VIOS run 'oem_setup_env' first)"
fi

# Circuit breaker and item status counters (SECONDS is an integer in ksh88 and a float in ksh93)
TO_STREAK=0; TO_TOTAL=0; SKIP_CNT=0; ERR_CNT=0; LOW_SPACE=0
CNT_TOTAL=0; CNT_OK=0; CNT_EMPTY=0; CNT_PERM=0; CNT_MISSING=0; CNT_TO_ITEM=0; CNT_SKIP_ITEM=0; CNT_FAILED=0; CNT_NA=0; CNT_REDACTED=0
ITEM_SEQ=0
CUR_SECTION="header"
START_SEC=${SECONDS%.*}
if [ "$GLOBAL_TIMEOUT" -gt 0 ]; then
  DEADLINE=$(( START_SEC + GLOBAL_TIMEOUT ))
else
  DEADLINE=0
fi

# Raw timezone-preserving timestamps (never fabricate a timezone suffix)
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
}

HOST=$(hostname 2>/dev/null | cut -d. -f1)
[ -n "$HOST" ] || HOST=$(uname -n 2>/dev/null)
[ -n "$HOST" ] || HOST="unknown"
MY_PGID=$(ps -eo pid,pgid 2>/dev/null | awk -v me="$$" 'NR > 1 && $1 == me && $2 ~ /^[0-9]+$/ {print $2; exit}')
# kill_tree uses the PGID column only to confirm PIDs whose parent link is gone
if [ -n "$MY_PGID" ]; then PS_FMT="pid,ppid,pgid"; PS_PGID=1; else PS_FMT="pid,ppid"; PS_PGID=0; fi
MACH_INFO=$(uname -uM 2>/dev/null)
MACH_SN=$(echo "$MACH_INFO" | awk '{
  s = $2; sub(/^IBM,/, "", s); sub(/^0[0-9]/, "", s)
  if (s ~ /^[A-Za-z0-9_-]+$/) print s
}')
TS=$(date '+%Y-%m-%d_%H-%M-%S')
START_TIME=$(date '+%Y-%m-%d %H:%M:%S')
START_TIME_RAW=$(iso_now_raw)
DATE_RAW=$(date 2>/dev/null)
TZ_RAW=$(tz_raw_str)
CUR_YEAR=$(date '+%Y' 2>/dev/null)
CLOCK_WARN=""
if is_uint "$CUR_YEAR" && [ "$CUR_YEAR" -lt 2020 ]; then
  CLOCK_WARN="system clock appears uninitialized or out of date ($START_TIME)"
fi

#------------------------------ Helper Functions ------------------------------
# Note: this script may be piped via "ksh -s" over SSH;
#       child commands must redirect stdin from /dev/null (run_to does this).

have() {
  case $1 in
    */*) [ -x "$1" ]; return $? ;;
  esac
  _ifs=$IFS; IFS=:
  for _d in $PATH; do
    if [ -n "$_d" ] && [ -x "$_d/$1" ] && [ ! -d "$_d/$1" ]; then
      IFS=$_ifs; return 0
    fi
  done
  IFS=$_ifs
  return 1
}

calc_sha256() {
  _cs_f="$1"
  [ -r "$_cs_f" ] || { printf ''; return 0; }
  if have sha256sum; then
    sha256sum "$_cs_f" 2>/dev/null | awk '{print tolower($1)}'
  elif have csum; then
    csum -h SHA256 "$_cs_f" 2>/dev/null | awk '{print tolower($1)}'
  elif have shasum; then
    shasum -a 256 "$_cs_f" 2>/dev/null | awk '{print tolower($1)}'
  elif have openssl; then
    openssl dgst -sha256 "$_cs_f" 2>/dev/null | awk '{print tolower($NF)}'
  else
    printf ''
  fi
}

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 }'
}

# Streaming POSIX awk credential redactor (covers 20 credential classes):
# PEM private keys, shadow/AIX passwd hashes, URL credentials, Auth/Cookie/API-key headers,
# Bearer/JWT/cloud tokens (AWS/GitHub/GitLab/sk-/xox*-), SNMP communities & XML tags,
# SQL IDENTIFIED BY, CLI long/short password flags, mount/iSCSI/DB env/KV secrets & lsattr secrets.
# Writes redacted output to $2 and "1"/"0" to $3.
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, tok) {
    out = ""; rest = s
    while (match(rest, re)) {
      tok = substr(rest, RSTART, RLENGTH)
      if (RLENGTH >= min_len) {
        out = out substr(rest, 1, RSTART - 1) label
        rest = substr(rest, RSTART + RLENGTH)
        changed = 1
      } else {
        out = out substr(rest, 1, RSTART + RLENGTH - 1)
        rest = substr(rest, RSTART + RLENGTH)
      }
    }
    return out rest
  }
  function mask_hashes(s,   out, rest, colon_n, sf) {
    # Classic /etc/shadow colon-delimited entry (user:hash:days:min:max:...)
    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
      }
    }
    # Crypt/shadow hashes ($1$, $2a$, $5$, $6$, $y$, $gy$, $md5$, $sha256$)
    s = mask_re_len(s, "\\$(1|2[aby]|5|6|y|gy|md5|sha256|sha512)\\$[A-Za-z0-9./$+=_-]+", 12, "[REDACTED:HASH]")
    # AIX /etc/security/passwd hashes ({ssha256}, {ssha512}, {ssha1}, {smd5}, {sblowfish})
    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) {
    # XML SNMP/auth tags
    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
    # SNMP config directives (rocommunity / rwcommunity / community / trapsink)
    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
        }
      }
    }
    # SQL IDENTIFIED BY <secret>
    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_and_lsattr(s,   out, rest, head, tail, val, qch, qpos, k1, v2) {
    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
    }
    s = out rest
    # AIX lsattr tabular line: "<sensitive_attr> <value> <description> True|False"
    if (match(s, /^[ \t]*[A-Za-z0-9_.-]+[ \t]+[^ \t]+/)) {
      k1 = tolower(substr(s, 1, RLENGTH))
      sub(/^[ \t]+/, "", k1)
      sub(/[ \t]+.*$/, "", k1)
      if (k1 ~ /(^|[_.-])(password|passwd|chap_password|chap_secret|secret|snmp_community|community|auth_token|api_key|private_key|passphrase|authpass|privpass)$/) {
        if (match(s, /^[ \t]*[A-Za-z0-9_.-]+[ \t]+/)) {
          head = substr(s, 1, RLENGTH)
          tail = substr(s, RLENGTH + 1)
          if (match(tail, /^[^ \t]+/)) {
            v2 = substr(tail, 1, RLENGTH)
            if (!is_safe_val(v2)) {
              s = head "[REDACTED]" substr(tail, RLENGTH + 1)
              changed = 1
            }
          }
        }
      }
    }
    return s
  }
  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
    }
    # Fast-path pre-check: skip expensive regex loops on ordinary telemetry lines
    low_fast = tolower(line)
    if (low_fast ~ /(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_and_lsattr(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|0516-010|0518-506|requires root' "$1" >/dev/null 2>&1
}

# Terminate a timed-out or interrupted command subshell (ROOT_PID) and its descendants:
#   1) Snapshot the live descendant tree of ROOT_PID by PPID links (all process groups,
#      so children that called setpgid / setsid are included), children first, ROOT_PID
#      last, together with each PID's PGID, after verifying ROOT_PID's PPID is still $$
#      (or PPID 1 with PGID == MY_PGID if $$ was SIGKILLed), and send SIGTERM.
#   2) Poll up to WAIT_SEC (>= 1) seconds for those processes to exit.
#   3) Right before SIGKILL re-scan live 'ps' and signal only
#        - ROOT_PID, if its PPID is still $$ (or PPID 1 with matching PGID if $$ died)
#          and it still carries the PGID recorded in step 1, plus its live descendants;
#        - non-root snapshot PIDs whose parent exited (PPID 1 / parent gone) that still
#          carry the PGID recorded in step 1, plus their live descendants;
#      so a PID that exited and was reused by an unrelated process is never signaled.
kill_tree() {
  _kwait=$1; _kroot=$2
  [ -n "$_kroot" ] || return 0
  _ksnap=$(ps -eo "$PS_FMT" 2>/dev/null | awk -v root="$_kroot" -v me="$$" -v wpid="$_wpid" -v mypg="$MY_PGID" -v usepg="$PS_PGID" '
    NR > 1 && $1 ~ /^[0-9]+$/ {
      if ($1 == me) { me_alive = 1; next }
      if (wpid != "" && $1 == wpid) next
      pp[$1] = $2; pg[$1] = (NF >= 3 ? $3 : "-")
    }
    END {
      if (!(root in pp)) exit
      if (me_alive) {
        if (pp[root] != me) exit
      } else {
        if (pp[root] != "1" || usepg != "1" || pg[root] != mypg) exit
      }
      n = 1; list[1] = root; seen[root] = 1; changed = 1
      while (changed) {
        changed = 0
        for (p in pp) if (!(p in seen) && (pp[p] in seen)) { seen[p] = 1; list[++n] = p; changed = 1 }
      }
      for (i = n; i >= 1; i--) printf "%s:%s ", list[i], pg[list[i]]
    }')
  [ -n "$_ksnap" ] || return 0
  for _kp in $_ksnap; do kill -TERM "${_kp%%:*}" 2>/dev/null; done
  _krem=""
  _kn=0
  while [ "$_kn" -lt "$_kwait" ]; do
    sleep 1
    _kn=$((_kn + 1))
    _krem=$(ps -eo "$PS_FMT" 2>/dev/null | awk -v root="$_kroot" -v me="$$" -v wpid="$_wpid" -v snap="$_ksnap" -v usepg="$PS_PGID" '
      BEGIN {
        n = split(snap, a, " ")
        for (i = 1; i <= n; i++) if (split(a[i], b, ":") == 2) opg[b[1]] = b[2]
      }
      NR > 1 && $1 ~ /^[0-9]+$/ {
        if ($1 == me) { me_alive = 1; next }
        if (wpid != "" && $1 == wpid) next
        pp[$1] = $2; pg[$1] = (NF >= 3 ? $3 : "-")
      }
      END {
        n = 0
        if (root in pp) {
          if (me_alive) {
            if (pp[root] == me && (usepg != "1" || pg[root] == opg[root])) { list[++n] = root; seen[root] = 1 }
          } else {
            if (pp[root] == "1" && usepg == "1" && pg[root] == opg[root]) { list[++n] = root; seen[root] = 1 }
          }
        }
        if (usepg == "1") {
          for (p in opg) {
            if (p != root && (p in pp) && !(p in seen) && opg[p] != "-" && pg[p] == opg[p] &&
                (pp[p] == "1" || !(pp[p] in pp))) { list[++n] = p; seen[p] = 1 }
          }
        }
        changed = 1
        while (changed) {
          changed = 0
          for (p in pp) if (!(p in seen) && (pp[p] in seen)) { seen[p] = 1; list[++n] = p; changed = 1 }
        }
        for (i = n; i >= 1; i--) printf "%s ", list[i]
      }')
    [ -n "$_krem" ] || return 0
  done
  for _kp in $_krem; do kill -KILL "$_kp" 2>/dev/null; done
}

# _IN_MAIN is 1 only in the main shell. run_to sets it to 0 around every fork.
_IN_MAIN=1; _SIG_PENDING=""
_pid=""; _wpid=""; TMPD=""
cleanup() {
  [ "$_IN_MAIN" = 1 ] || return 0
  [ -n "$TMPD" ] && rm -rf "$TMPD" 2>/dev/null
}

on_signal() {
  if [ "$_IN_MAIN" != 1 ]; then _SIG_PENDING=1; return 0; fi
  trap '' 1 2 15
  [ -n "$_wpid" ] && kill -TERM "$_wpid" 2>/dev/null
  kill_tree 1 "$_pid"
  _pid=""
  if [ -n "$_wpid" ]; then
    wait "$_wpid" 2>/dev/null
    _wpid=""
  fi
  if [ -n "$LOG" ] && [ -f "$LOG" ]; then
    printf '\n*** INTERRUPTED by signal at %s (%s)\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$(iso_now_raw)" >> "$LOG"
  fi
  cleanup
  exit 130
}

# Run command with timeout watchdog to prevent hanging the check.
# Returns the command's rc, 124 on timeout, 125 if skipped (circuit breaker, -T deadline
# or low disk space).
RT_OUT=""
run_to() {
  _to=$1; shift
  _cmd="$*"
  _why=""
  if [ "$TO_STREAK" -ge "$MAX_TO_STREAK" ]; then
    _why="$MAX_TO_STREAK consecutive timeouts in this section"
  elif [ "$TO_TOTAL" -ge "$MAX_TO_TOTAL" ]; then
    _why="$MAX_TO_TOTAL timeouts in this run"
  elif [ "$DEADLINE" -gt 0 ] && [ "${SECONDS%.*}" -ge "$DEADLINE" ]; then
    _why="run deadline ${GLOBAL_TIMEOUT}s reached"
  elif [ "${LOW_SPACE:-0}" -eq 1 ]; then
    _why="less than $MIN_KEEP_MB MB free in output directory"
  fi
  if [ -n "$_why" ]; then
    SKIP_CNT=$((SKIP_CNT + 1))
    if [ -n "$RT_OUT" ]; then
      printf '*** SKIPPED (%s): %s\n' "$_why" "$_cmd" >> "$RT_OUT"
    else
      printf '*** SKIPPED (%s): %s\n' "$_why" "$_cmd"
    fi
    return 125
  fi
  _IN_MAIN=0
  if [ -n "$RT_OUT" ]; then
    ( trap - 0 15; trap '' 1 2; eval "$_cmd"; exit $? ) </dev/null >> "$RT_OUT" 2>&1 &
  else
    ( trap - 0 15; trap '' 1 2; eval "$_cmd"; exit $? ) </dev/null 2>&1 &
  fi
  _pid=$!
  _flag="$TMPD/to.$_pid"
  (
    trap - 0
    trap '' 1 2
    _reaped_sl=$!
    trap 'trap "" 15
          _s=$!
          if [ -n "$_s" ] && [ "$_s" != "$_reaped_sl" ]; then
            kill -TERM "$_s" 2>/dev/null
            wait "$_s" 2>/dev/null
          fi
          exit 0' 15
    [ -n "$_SIG_PENDING" ] && exit 0
    _n=0
    while :; do
      sleep 1 &
      wait "$!" 2>/dev/null
      _reaped_sl=$!
      kill -0 "$_pid" 2>/dev/null || exit 0
      _n=$((_n + 1))
      [ "$_n" -lt "$_to" ] || break
    done
    trap '' 15
    : > "$_flag"
    kill_tree 2 "$_pid"
  ) </dev/null >/dev/null 2>&1 &
  _wpid=$!
  _IN_MAIN=1
  [ -n "$_SIG_PENDING" ] && on_signal
  wait "$_pid"
  _rc=$?
  _pid=""
  _timed=0
  if [ -f "$_flag" ]; then
    _timed=1
    wait "$_wpid" 2>/dev/null
  else
    kill -TERM "$_wpid" 2>/dev/null
    wait "$_wpid" 2>/dev/null
  fi
  _wpid=""
  rm -f "$_flag"
  if [ $_timed -eq 1 ]; then
    TO_STREAK=$((TO_STREAK + 1)); TO_TOTAL=$((TO_TOTAL + 1))
    if [ -n "$RT_OUT" ]; then
      printf '*** TIMEOUT: command exceeded %s seconds: %s\n' "$_to" "$_cmd" >> "$RT_OUT"
    else
      printf '*** TIMEOUT: command exceeded %s seconds: %s\n' "$_to" "$_cmd"
    fi
    return 124
  fi
  TO_STREAK=0
  return $_rc
}

# Compute errpt -s timestamp (mmddHHMMyy) for N days ago using awk.
date_ago() {
  date '+%Y %m %d' | awk -v n="$1" '{
    y = $1 + 0; m = $2 + 0; d = $3 + 0; n += 0
    if (y < 1971 || y > 2037) exit
    split("31 28 31 30 31 30 31 31 30 31 30 31", ml, " ")
    while (n > 0) {
      if (n < d) { d -= n; n = 0 }
      else {
        n -= d; m--
        if (m < 1) { m = 12; y-- }
        dm = ml[m]
        if (m == 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)) dm = 29
        d = dm
      }
    }
    if (y < 1971 || y > 2037) exit
    printf "%02d%02d0000%02d\n", m, d, y % 100
  }'
}

# Return 0 if target path resides on a network/automount file system
is_netfs_dir() {
  mount </dev/null 2>/dev/null | awk -v d="$1" '
    NR > 2 && NF >= 4 {
      mp = ($1 ~ /^\//) ? $2 : $3
      vfs = ($1 ~ /^\//) ? $3 : $4
      if (d == mp || (mp == "/" && substr(d, 1, 1) == "/") || substr(d, 1, length(mp) + 1) == mp "/") {
        if (length(mp) >= best) { best = length(mp); bvfs = vfs }
      }
    }
    END { if (bvfs ~ /^(nfs|cifs|smbfs|autofs)/) exit 0; exit 1 }'
}

# Output directory must be owned by the running user (root when uid=0), not a symlink,
# and not writable by group/others.
dir_ok() {
  [ -d "$1" ] || return 1
  [ -L "$1" ] && return 1
  _do_owner="$RUN_AS_USER"
  [ "$IS_ROOT" = "true" ] && _do_owner="root"
  case $(ls -ld "$1" 2>/dev/null | awk '{print $1 " " $3}') in
    d????-??-*" $_do_owner") return 0 ;;
  esac
  return 1
}

# Free space (MB) of the file system holding the output directory (AIX 'MB blocks' + POSIX header-aware)
free_mb() {
  df -m "$OUTDIR" </dev/null 2>/dev/null | awk '
    NR == 1 {
      if ($0 ~ /MB[ \t]+blocks/) { col = 3; next }
      for (i = 1; i <= NF; i++) {
        h = tolower($i)
        if (h == "free" || h == "available" || h == "avail") { col = i; break }
      }
      if (!col) col = 3
      next
    }
    NR == 2 {
      v = $(col)
      if (v ~ /^[0-9.]+$/) print int(v)
    }'
}

chk_space() {
  if [ "$LOW_SPACE" -eq 0 ]; then
    _fmb=$(free_mb)
    if [ -n "$_fmb" ] && [ "$_fmb" -lt "$MIN_KEEP_MB" ]; then LOW_SPACE=1; fi
  fi
}

# Print section header
sec() {
  TO_STREAK=0
  CUR_SECTION="$1"
  chk_space
  {
    printf '\n================================================================================\n'
    printf '# %s\n' "$1"
    printf '================================================================================\n'
  } >> "$LOG"
}

# Print simulated command prompt: "[YYYY-MM-DD HH:MM:SS] user@host:/> cmd"
prompt() {
  _pts=$2
  [ -n "$_pts" ] || _pts=$(date '+%Y-%m-%d %H:%M:%S')
  printf '\n[%s] %s@%s:/> %s\n' "$_pts" "$RUN_AS_USER" "$HOST" "$1" >> "$LOG"
}

skip_note() {
  printf '\n*** SKIP %s\n' "$*" >> "$LOG"
}

info_note() {
  printf '\n*** NOTE %s\n' "$*" >> "$LOG"
}

is_internal_fn() {
  case "$1" in
    disk_summary|errpt_top|errpt_full_capped|ps_ef_cnt|ps_ef_out|ps_top_cpu|ps_top_mem|fs_automount_check|crontab_safe|cat_hosts_safe|ulimit_safe|security_limits_safe|vioshc_status_safe)
      return 0 ;;
  esac
  return 1
}

record_item_meta() {
  _rm_sec="$1"; _rm_cmd="$2"; _rm_ts_raw="$3"; _rm_rc="$4"; _rm_dur="$5"; _rm_st="$6"; _rm_red="$7"
  ITEM_SEQ=$((ITEM_SEQ + 1))
  CNT_TOTAL=$((CNT_TOTAL + 1))
  case "$_rm_st" 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_TO_ITEM=$((CNT_TO_ITEM + 1)) ;;
    skipped) CNT_SKIP_ITEM=$((CNT_SKIP_ITEM + 1)) ;;
    not_applicable) CNT_NA=$((CNT_NA + 1)) ;;
    failed) CNT_FAILED=$((CNT_FAILED + 1)) ;;
  esac
  if [ "$_rm_red" = "1" ]; then
    CNT_REDACTED=$((CNT_REDACTED + 1))
    _rm_red_bool="true"
  else
    _rm_red_bool="false"
  fi
  _j_sec=$(printf '%s' "$_rm_sec" | json_escape)
  _j_cmd=$(printf '%s' "$_rm_cmd" | json_escape)
  _j_ts=$(printf '%s' "$_rm_ts_raw" | json_escape)
  _j_st=$(printf '%s' "$_rm_st" | json_escape)
  printf '{"seq":%s,"section":%s,"command":%s,"started_at_raw":%s,"duration_sec":%s,"exit_code":%s,"status":%s,"redacted":%s}\n' \
    "$ITEM_SEQ" "$_j_sec" "$_j_cmd" "$_j_ts" "$_rm_dur" "$_rm_rc" "$_j_st" "$_rm_red_bool" >> "$TMPD/items.jsonl"
}

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

# Core runner: _run MODE NAME [-t SEC] [-p TEXT] [-i] [-R] CMD
#   -R : force redacted=1 in item metadata (e.g., restricted ps / crontab summary)
_run() {
  _mode=$1; _name=$2; shift 2
  _to=$CMD_TIMEOUT; _ptxt=""; _ign=0; _force_red=0
  while :; do
    case $1 in
      -t) _to=$2; shift 2 ;;
      -p) _ptxt=$2; shift 2 ;;
      -i) _ign=1; shift ;;
      -R) _force_red=1; shift ;;
      *)  break ;;
    esac
  done
  if [ "$_to" -ge 120 ] && [ "$_to" -lt "$CMD_TIMEOUT" ]; then _to=$CMD_TIMEOUT; fi
  _cmd="$*"
  _disp="${_ptxt:-$_cmd}"
  _ts=$(date '+%Y-%m-%d %H:%M:%S')
  _ts_raw=$(iso_now_raw)
  [ "$_mode" = quiet ] || prompt "$_disp" "$_ts"
  _t0=${SECONDS%.*}

  if [ -n "$_name" ]; then
    _raw_f="$TMPD/$_name.raw"
    _red_f="$TMPD/$_name"
  else
    _raw_f="$TMPD/_cmd.raw"
    _red_f="$TMPD/_cmd.red"
  fi
  : > "$_raw_f"
  : > "$_red_f"

  # Detect missing primary binary before forking watchdog
  _first_tok=$(printf '%s\n' "$_cmd" | awk '{print $1}')
  _missing_bin=0
  if [ -n "$_first_tok" ] && ! is_internal_fn "$_first_tok"; then
    case "$_first_tok" in
      for|if|while|case|\{|\() ;;
      *)
        if ! have "$_first_tok"; then
          _missing_bin=1
        fi ;;
    esac
  fi

  if [ "$_missing_bin" -eq 1 ]; then
    _rc=127
    printf '[command missing: %s]\n' "$_first_tok" > "$_raw_f"
  else
    RT_OUT="$_raw_f"
    run_to "$_to" "$_cmd"
    _rc=$?
    RT_OUT=""
  fi
  _sec=$(( ${SECONDS%.*} - _t0 ))
  [ "$_sec" -lt 0 ] && _sec=0

  _red_flag=0
  if [ -s "$_raw_f" ]; then
    redact_file "$_raw_f" "$_red_f" "$TMPD/_red.flag"
    _rfv=$(cat "$TMPD/_red.flag" 2>/dev/null)
    [ "$_rfv" = "1" ] && _red_flag=1
  fi
  [ "$_force_red" -eq 1 ] && _red_flag=1
  rm -f "$_raw_f" "$TMPD/_red.flag"

  _status=$(classify_aix_status "$_rc" "$_red_f" "$_ign")
  if [ "$_ign" -eq 0 ] && [ "$_rc" -ne 0 ] && [ "$_rc" -ne 124 ] && [ "$_rc" -ne 125 ] && [ "$_rc" -ne 126 ]; then
    ERR_CNT=$((ERR_CNT + 1))
  fi
  if [ -n "$_name" ]; then
    printf '%s\n%s\n%s\n%s\n%s\n%s\n' "$_ts" "$_rc" "$_sec" "$_status" "$_red_flag" "$_ts_raw" > "$TMPD/$_name.meta"
  fi
  if [ "$_mode" != quiet ]; then
    [ -s "$_red_f" ] && cat "$_red_f" >> "$LOG"
    printf '#@ rc=%s sec=%s status=%s redacted=%s\n' "$_rc" "$_sec" "$_status" "$_red_flag" >> "$LOG"
    record_item_meta "$CUR_SECTION" "$_disp" "$_ts_raw" "$_rc" "$_sec" "$_status" "$_red_flag"
    if [ -n "$_name" ]; then
      case $_rc in
        124|125) printf '*** SKIP follow-up checks based on the output above\n' >> "$LOG" ;;
      esac
    else
      : > "$_red_f"
    fi
  fi
  return $_rc
}

run_cmd() { _run log "" "$@"; }
run_save() { _rn=$1; shift; _run log "$_rn" "$@"; }
capture() { _rn=$1; shift; _run quiet "$_rn" "$@"; }

replay() {
  _m="$TMPD/$1.meta"
  _r_ts=$(sed -n 1p "$_m" 2>/dev/null)
  _r_rc=$(sed -n 2p "$_m" 2>/dev/null)
  _r_sec=$(sed -n 3p "$_m" 2>/dev/null)
  _r_st=$(sed -n 4p "$_m" 2>/dev/null)
  _r_red=$(sed -n 5p "$_m" 2>/dev/null)
  _r_ts_raw=$(sed -n 6p "$_m" 2>/dev/null)
  prompt "$2" "$_r_ts"
  cat "$TMPD/$1" >> "$LOG" 2>/dev/null
  printf '#@ rc=%s sec=%s status=%s redacted=%s\n' "${_r_rc:-0}" "${_r_sec:-0}" "${_r_st:-ok}" "${_r_red:-0}" >> "$LOG"
  record_item_meta "$CUR_SECTION" "$2" "${_r_ts_raw:-$_r_ts}" "${_r_rc:-0}" "${_r_sec:-0}" "${_r_st:-ok}" "${_r_red:-0}"
}

usable() {
  [ "$(sed -n 2p "$TMPD/$1.meta" 2>/dev/null)" = "0" ]
}

need() {
  usable "$1" && return 0
  _nrc=$(sed -n 2p "$TMPD/$1.meta" 2>/dev/null)
  case $_nrc in
    124|125) ;;
    *) skip_note "$2: the command they are based on returned rc=${_nrc:-unknown}" ;;
  esac
  return 1
}

devs() {
  usable "$1" || return 0
  awk -v re="^$2[0-9]+\$" '$1 ~ re && $2 == "Available" {print $1}' "$TMPD/$1" 2>/dev/null
}

in_words() {
  case " $2 " in *" $1 "*) return 0 ;; esac
  return 1
}

lvm_q() {
  _lq=$1; shift
  _la="$*"
  run_cmd -i "$_lq -L${_la:+ $_la}"
  case $? in 0|124|125|127) return 0 ;; esac
  run_cmd "$_lq${_la:+ $_la}"
}

disk_summary() {
  : > "$TMPD/disk_pcm"
  _pv=""
  usable lspv_out && _pv="$TMPD/lspv_out"
  printf '%-10s %-16s %-22s %-14s %-15s %-7s %-7s %-10s %s\n' \
    "DISK" "VG" "PCM" "ALGORITHM" "RESERVE_POLICY" "Q_DEPTH" "HCHECK" "HCHK_MODE" "UNIQUE_ID"
  for _d in $DISK_LIST; do
    lsattr -El "$_d" -F "attribute value" 2>/dev/null | awk -v d="$_d" -v pv="$_pv" -v pf="$TMPD/disk_pcm" '
      BEGIN {
        vg = "-"
        if (pv != "") {
          while ((getline ln < pv) > 0) {
            if (split(ln, f, " ") >= 3 && f[1] == d) { vg = f[3]; break }
          }
          close(pv)
        }
      }
      { a[$1] = $2 }
      END {
        pcm = (a["PCM"] != "" ? a["PCM"] : "-")
        printf "%-10s %-16s %-22s %-14s %-15s %-7s %-7s %-10s %s\n",
          d, vg, pcm,
          (a["algorithm"] != "" ? a["algorithm"] : "-"),
          (a["reserve_policy"] != "" ? a["reserve_policy"] : "-"),
          (a["queue_depth"] != "" ? a["queue_depth"] : "-"),
          (a["hcheck_interval"] != "" ? a["hcheck_interval"] : "-"),
          (a["hcheck_mode"] != "" ? a["hcheck_mode"] : "-"),
          (a["unique_id"] != "" ? a["unique_id"] : "-")
        print d, pcm >> pf
      }'
  done
}

errpt_top() {
  printf '%6s %-10s %-2s %-2s %s\n' "COUNT" "IDENTIFIER" "T" "C" "RESOURCE_NAME"
  if usable errpt_out; then
    awk -v st="$ERRPT_START" '
      BEGIN {
        if (length(st) == 10 && st ~ /^[0-9]+$/) {
          sy = substr(st, 9, 2) + 0
          s = sprintf("%04d%s", (sy >= 69 ? 1900 + sy : 2000 + sy), substr(st, 1, 8))
        }
      }
      NR > 1 && NF >= 5 {
        if (s != "" && length($2) == 10 && $2 ~ /^[0-9]+$/) {
          ty = substr($2, 9, 2) + 0
          t = sprintf("%04d%s", (ty >= 69 ? 1900 + ty : 2000 + ty), substr($2, 1, 8))
          if (t < s) next
        }
        k = $1 " " $3 " " $4 " " $5; c[k]++
      }
      END {for (k in c) {split(k, f, " "); printf "%6d %-10s %-2s %-2s %s\n", c[k], f[1], f[2], f[3], f[4]}}' "$TMPD/errpt_out"
  else
    if [ -n "$ERRPT_START" ]; then errpt -s "$ERRPT_START"; else errpt; fi |
      awk 'NR > 1 && NF >= 5 {k = $1 " " $3 " " $4 " " $5; c[k]++}
           END {for (k in c) {split(k, f, " "); printf "%6d %-10s %-2s %-2s %s\n", c[k], f[1], f[2], f[3], f[4]}}'
  fi | sort -rn | head -20
}

errpt_cnt_since() {
  usable errpt_out || return 0
  awk -v st="$1" '
    function ts(v,  y) { y = substr(v, 9, 2) + 0; return sprintf("%04d%s", (y >= 69 ? 1900 + y : 2000 + y), substr(v, 1, 8)) }
    BEGIN { if (length(st) == 10 && st ~ /^[0-9]+$/) s = ts(st) }
    NR > 1 && NF >= 5 && length($2) == 10 && $2 ~ /^[0-9]+$/ { if (s == "" || ts($2) >= s) c++ }
    END { print c + 0 }' "$TMPD/errpt_out" 2>/dev/null
}

errpt_full_capped() {
  errpt -a | awk -v max="$ERRPT_MAX_LINES" '
    NR <= max { print; next }
    { print "*** TRUNCATED: errpt -a output exceeded " max " lines (automatic fallback limit); run with -d 0 for the full history"; exit }'
}

# Process helpers: strictly use restricted columns ('comm' basename only, never raw 'args'/'aux'/'-ef')
# to eliminate command-line plaintext credential leakage.
ps_ensure_safe() {
  if ! have ps; then
    printf '[command missing: ps]\n'
    return 127
  fi
  if [ ! -s "$TMPD/ps_safe" ]; then
    ps -eo user,pid,ppid,pcpu,pmem,vsz,tty,time,comm > "$TMPD/ps_safe"
  fi
}
ps_ef_cnt() {
  ps_ensure_safe || return $?
  awk 'NR > 1 {c++} END {print c + 0}' "$TMPD/ps_safe"
}
ps_ef_out() {
  ps_ensure_safe || return $?
  cat "$TMPD/ps_safe"
}
ps_top_cpu() {
  ps_ensure_safe || return $?
  head -n 1 "$TMPD/ps_safe"
  sed '1d' "$TMPD/ps_safe" | sort -rn -k 4,4 | head -n 10
}
ps_top_mem() {
  ps_ensure_safe || return $?
  head -n 1 "$TMPD/ps_safe"
  sed '1d' "$TMPD/ps_safe" | sort -rn -k 5,5 | head -n 10
}

# Crontab metadata-only collector: emit schedule + executable basename only;
# drop comments, env variable assignments, and command arguments.
crontab_safe() {
  if ! have crontab; then
    printf '[command missing: crontab]\n'
    return 127
  fi
  _cr_tmp="$TMPD/crontab_raw.$$"
  crontab -l > "$_cr_tmp" 2>&1
  _cr_rc=$?
  if [ "$_cr_rc" -ne 0 ]; then
    if grep -iE 'no crontab|can.?t open your crontab' "$_cr_tmp" >/dev/null 2>&1; then
      printf 'crontab_status=empty\ncrontab_active_entries=0\ncrontab_env_assignments_omitted=0\ncrontab_comments_omitted=0\n'
      rm -f "$_cr_tmp"
      return 0
    fi
    cat "$_cr_tmp"
    rm -f "$_cr_tmp"
    return "$_cr_rc"
  fi
  printf 'crontab_status=present\n'
  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
    }' "$_cr_tmp"
  rm -f "$_cr_tmp"
  return 0
}

cat_hosts_safe() {
  cat "${ROOT_PREFIX}/etc/hosts"
}

ulimit_safe() {
  ulimit -a
}

# Read-only resource limit extractor for /etc/security/limits (PIQS baseline).
# Strictly reads /etc/security/limits only (never /etc/security/passwd) and
# emits only stanzas containing standard resource-limit keys; output also
# passes through the 20-class streaming credential redactor.
security_limits_safe() {
  _slf="${ROOT_PREFIX}/etc/security/limits"
  if [ ! -f "$_slf" ] && [ ! -L "$_slf" ]; then
    printf '[not applicable: /etc/security/limits not present]\n'
    return 126
  fi
  if [ ! -r "$_slf" ]; then
    printf 'cannot open /etc/security/limits: Permission denied\n'
    return 1
  fi
  awk '
    /^[ \t]*$/ || /^[ \t]*\*/ || /^[ \t]*#/ { next }
    /^[ \t]*[A-Za-z0-9_.-]+:[ \t]*$/ {
      cur = $0
      sub(/^[ \t]+/, "", cur)
      sub(/[ \t]+$/, "", cur)
      pending = cur
      next
    }
    {
      ln = $0
      sub(/^[ \t]+/, "", ln)
      if (ln ~ /^(fsize|core|cpu|data|rss|stack|nofiles|threads|nproc)(_hard)?[ \t]*=/) {
        if (pending != "") { print pending; pending = "" }
        print "  " ln
      }
    }' "$_slf"
}

# Strictly read-only VIOS Health Checker (vioshc) status probe (never modifies VIOS config).
vioshc_status_safe() {
  _vhc=""
  if have vioshc; then
    _vhc="vioshc"
  elif [ -x "${ROOT_PREFIX}/usr/ios/sbin/vioshc" ]; then
    _vhc="${ROOT_PREFIX}/usr/ios/sbin/vioshc"
  elif [ -x "${ROOT_PREFIX}/usr/sbin/vioshc" ]; then
    _vhc="${ROOT_PREFIX}/usr/sbin/vioshc"
  else
    printf '[command missing: vioshc]\n'
    return 127
  fi
  _vh_tmp="$TMPD/vioshc_out.$$"
  "$_vhc" -l > "$_vh_tmp" 2>&1
  _vh_rc=$?
  if [ "$_vh_rc" -eq 0 ] && [ -s "$_vh_tmp" ]; then
    cat "$_vh_tmp"
    rm -f "$_vh_tmp"
    return 0
  fi
  if grep -iE 'usage:|illegal option|invalid option|unrecognized|requires an argument|missing' "$_vh_tmp" >/dev/null 2>&1; then
    : > "$_vh_tmp"
    "$_vhc" -v > "$_vh_tmp" 2>&1
    _vh_rc=$?
  fi
  cat "$_vh_tmp"
  rm -f "$_vh_tmp"
  return "$_vh_rc"
}

fs_automount_check() {
  awk -v mf="$TMPD/mount_out" '
    BEGIN {
      while ((getline ln < mf) > 0) {
        n = split(ln, f, " ")
        if (n >= 3 && f[1] != "node" && f[1] !~ /^-+$/) m[(f[1] ~ /^\//) ? f[2] : f[3]] = 1
      }
      close(mf)
      FS = ":"
    }
    /^#/ { for (i = 1; i <= NF; i++) if (tolower($i) == "automount") ac = i; next }
    ac {
      v = tolower($ac)
      if (v == "yes" || v == "true" || v == "automatic") { tot++; if (!($1 in m)) { print $1; miss++ } }
    }
    END {
      if (!ac) print "(AutoMount column not found in lsfs -c header)"
      else if (!miss) print "(none: all " (tot + 0) " AutoMount filesystems are mounted)"
    }' "$TMPD/lsfs_c"
}

#------------------------------ Output & Temp Dir -----------------------------
case $OUTFILE in
  "")    OUTDIR=$BASEDIR ;;
  *.log) OUTDIR=$(dirname "$OUTFILE") ;;
  *)     OUTDIR=${OUTFILE%/}; OUTFILE="" ;;
esac
[ -n "$OUTDIR" ] || OUTDIR=/
if is_netfs_dir "$OUTDIR"; then
  echo "ERROR: output directory $OUTDIR is on a network/automount file system; choose a local path (e.g. /tmp/healthcheck)" >&2
  exit 2
fi
[ -d "$OUTDIR" ] || mkdir -p "$OUTDIR" 2>/dev/null
if [ ! -d "$OUTDIR" ]; then
  echo "ERROR: cannot create directory $OUTDIR" >&2
  exit 2
fi
if dir_ok "$OUTDIR"; then :; else
  echo "ERROR: $OUTDIR must be a real directory owned by the running user and not writable by group/others" >&2
  echo "       (use a dedicated directory, e.g. -o /tmp/healthcheck)" >&2
  exit 2
fi

FREE_MB=$(free_mb)
if [ -z "$FREE_MB" ]; then
  echo "WARNING: cannot determine free space of $OUTDIR, continuing" >&2
elif [ "$FREE_MB" -lt "$MIN_FREE_MB" ]; then
  echo "ERROR: only ${FREE_MB} MB free in $OUTDIR (need >= ${MIN_FREE_MB} MB); use -o to choose another directory" >&2
  exit 2
fi

if [ -z "$OUTFILE" ]; then
  if [ "$HOST" = "localhost" ] && [ -n "$MACH_SN" ]; then
    OUTFILE="${OUTDIR%/}/${HOST}_${MACH_SN}_${TS}.log"
  else
    OUTFILE="${OUTDIR%/}/${HOST}_${TS}.log"
  fi
fi
if [ -f "$OUTFILE" ] || [ -d "$OUTFILE" ] || [ -L "$OUTFILE" ]; then
  echo "ERROR: $OUTFILE already exists, refusing to overwrite" >&2
  exit 2
fi

_tmpd="${OUTDIR%/}/.tmp_$$"
if mkdir -m 700 "$_tmpd" 2>/dev/null; then
  TMPD=$_tmpd
else
  echo "ERROR: cannot create temp directory $_tmpd" >&2
  exit 2
fi
: > "$TMPD/items.jsonl"
trap 'cleanup' 0
trap 'on_signal' 1 2 15

LOG="$OUTFILE"
: > "$LOG" || { echo "ERROR: cannot write to $LOG" >&2; exit 2; }
if [ $STDOUT_MODE -eq 0 ]; then
  echo "[$SCRIPT_FILE] Collecting check output on $HOST -> $LOG ..."
  if [ -n "$PRIV_WARN" ]; then
    echo "[$SCRIPT_FILE] WARNING: $PRIV_WARN" >&2
  fi
fi
renice -n 10 -p $$ >/dev/null 2>&1

SCRIPT_SELF_SHA256=""
[ -n "$SCRIPT_SELF_PATH" ] && SCRIPT_SELF_SHA256=$(calc_sha256 "$SCRIPT_SELF_PATH")

#============================== Log Header ====================================
IOSCLI="${ROOT_PREFIX}/usr/ios/cli/ioscli"
CLMGR="${ROOT_PREFIX}/usr/es/sbin/cluster/utilities/clmgr"
CLSHOWSRV="${ROOT_PREFIX}/usr/es/sbin/cluster/utilities/clshowsrv"
CLTOPINFO="${ROOT_PREFIX}/usr/es/sbin/cluster/utilities/cltopinfo"
CLRGINFO="${ROOT_PREFIX}/usr/es/sbin/cluster/utilities/clRGinfo"
MMGETSTATE="${ROOT_PREFIX}/usr/lpp/mmfs/bin/mmgetstate"
MMLSMOUNT="${ROOT_PREFIX}/usr/lpp/mmfs/bin/mmlsmount"
ERRDEMON="${ROOT_PREFIX}/usr/lib/errdemon"
DUMPCHECK="${ROOT_PREFIX}/usr/lib/ras/dumpcheck"

IS_VIOS=0
[ -x "$IOSCLI" ] && IS_VIOS=1
IS_HA=0
if [ -x "$CLMGR" ] || [ -x "$CLSHOWSRV" ]; then
  IS_HA=1
fi

capture oslevel_s "oslevel -s"
if [ $IS_VIOS -eq 1 ]; then
  capture ioslevel -i -t 60 "$IOSCLI ioslevel"
fi
if [ "$ERRPT_DAYS" -gt 0 ]; then
  ERRPT_DESC="errpt -a last $ERRPT_DAYS days"
else
  ERRPT_DESC="errpt -a full"
fi
if [ "$GLOBAL_TIMEOUT" -gt 0 ]; then
  DEADLINE_DESC="${GLOBAL_TIMEOUT}s"
else
  DEADLINE_DESC="none"
fi

COMPONENTS=""
[ $IS_VIOS -eq 1 ] && COMPONENTS="$COMPONENTS VIOS"
[ $IS_HA -eq 1 ] && COMPONENTS="$COMPONENTS PowerHA"
[ -x "$MMGETSTATE" ] && COMPONENTS="$COMPONENTS GPFS"
have pcmpath && COMPONENTS="$COMPONENTS SDDPCM"
have powermt && COMPONENTS="$COMPONENTS PowerPath"
have dlnkmgr && COMPONENTS="$COMPONENTS HDLM"
[ -n "$COMPONENTS" ] || COMPONENTS=" -"

OS_LEVEL_STR=$(head -1 "$TMPD/oslevel_s" 2>/dev/null)
VIOS_LEVEL_STR=""
[ $IS_VIOS -eq 1 ] && VIOS_LEVEL_STR=$(head -1 "$TMPD/ioslevel" 2>/dev/null)

{
  printf '================================================================================\n'
  printf 'AIX CHECK LOG\n'
  printf 'SCHEMA     : %s\n' "$SCHEMA_VERSION"
  printf 'HOSTNAME   : %s\n' "$HOST"
  printf 'START_TIME : %s\n' "$START_TIME"
  printf 'START_RAW  : %s\n' "$START_TIME_RAW"
  printf 'DATE_RAW   : %s\n' "$DATE_RAW"
  if [ -n "$CLOCK_WARN" ]; then
    printf 'CLOCK_NOTE : WARNING - %s\n' "$CLOCK_WARN"
  fi
  printf 'TIMEZONE   : %s\n' "$TZ_RAW"
  printf 'RUN_AS     : %s (uid=%s, is_root=%s, privilege_mode=%s)\n' "$RUN_AS_USER" "$RUN_AS_UID" "$IS_ROOT" "$PRIVILEGE_MODE"
  if [ -n "$PRIV_WARN" ]; then
    printf 'PRIV_NOTE  : WARNING - %s\n' "$PRIV_WARN"
  fi
  printf 'OS_LEVEL   : %s\n' "$OS_LEVEL_STR"
  printf 'MACHINE    : %s\n' "$MACH_INFO"
  if [ $IS_VIOS -eq 1 ]; then
    printf 'VIOS_LEVEL : %s\n' "$VIOS_LEVEL_STR"
  fi
  printf 'COMPONENTS :%s\n' "$COMPONENTS"
  printf 'REDACTION  : applied (collector_default; ps_comm_only, crontab_metadata_only, streaming_secret_mask)\n'
  printf 'COLLECTOR  : %s %s (cmd timeout %ss, run deadline %s, %s)\n' \
    "$SCRIPT_FILE" "$VERSION" "$CMD_TIMEOUT" "$DEADLINE_DESC" "$ERRPT_DESC"
  printf 'OPTIONS    : t=%s T=%s d=%s A=%s s=%s E=%s\n' \
    "$CMD_TIMEOUT" "$GLOBAL_TIMEOUT" "$ERRPT_DAYS" "$ALL_DISKS" "$STDOUT_MODE" "$ERR_EXIT"
  printf '================================================================================\n'
} >> "$LOG"

#============================== 00. VIOS Mappings =============================
if [ $IS_VIOS -eq 1 ]; then
  sec "00. VIOS Mappings"
  replay ioslevel "/usr/ios/cli/ioscli ioslevel"
  run_cmd -i -t 300 -p "/usr/ios/cli/ioscli lsmap -all" "$IOSCLI lsmap -all"
  run_cmd -i -t 300 -p "/usr/ios/cli/ioscli lsmap -npiv -all" "$IOSCLI lsmap -npiv -all"
  run_cmd -i -t 300 -p "/usr/ios/cli/ioscli lsmap -all -net" "$IOSCLI lsmap -all -net"
  run_save lsnports_out -i -p "/usr/ios/cli/ioscli lsnports" "$IOSCLI lsnports"
  run_cmd -i -p "/usr/ios/cli/ioscli viosbr -view -list" "$IOSCLI viosbr -view -list"
  run_cmd -i -t 60 -p "vioshc (read-only status check)" vioshc_status_safe
fi

#============================== 01. System & Device Overview ==================
sec "01. System & Device Overview"
run_cmd "uname -uM"
replay oslevel_s "oslevel -s"
if have lparstat; then
  run_cmd -i "lparstat -i"
fi
run_cmd "lsattr -El sys0"
# FLRTVC standard fileset & efix inventory (lslpp -Lqc + emgr -lv3; fallback to emgr -l only if -lv3 unsupported)
run_cmd -i -t 120 "lslpp -Lqc"
run_save emgr_lv3 -i "emgr -lv3"
_emrc=$?
if [ $_emrc -ne 0 ] && [ $_emrc -ne 124 ] && [ $_emrc -ne 125 ] && [ $_emrc -ne 127 ]; then
  if grep -iE 'usage:|illegal option|invalid option|not recognized' "$TMPD/emgr_lv3" >/dev/null 2>&1; then
    info_note "emgr -lv3 rejected by this emgr build; falling back to emgr -l"
    run_cmd -i "emgr -l"
  fi
fi
run_save lsdev_all "lsdev"
capture lsdev_parent -i -t 60 'lsdev -C -F "name:status:parent"'
run_cmd "lsdev -C -S d"

#============================== 02. Error Report ==============================
sec "02. Error Report"
run_save errpt_out "errpt"
_ecap_p="errpt -a | head -n $ERRPT_MAX_LINES"
ERRPT_START=""
if [ "$ERRPT_DAYS" -gt 0 ]; then
  ERRPT_START=$(date_ago "$ERRPT_DAYS")
  case $ERRPT_START in
    [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) ;;
    *) ERRPT_START="" ;;
  esac
  if [ -n "$ERRPT_START" ]; then
    run_cmd -i -t 300 "errpt -a -s $ERRPT_START"
    _erc=$?
    if [ $_erc -ne 0 ] && [ $_erc -ne 124 ] && [ $_erc -ne 125 ] && [ $_erc -ne 127 ]; then
      _ecnt=$(errpt_cnt_since "$ERRPT_START")
      if [ "$_ecnt" = "0" ]; then
        info_note "errpt -a -s returned rc=$_erc; the cached 'errpt' has no entry since $ERRPT_START, nothing is missing"
      else
        ERRPT_START=""
        info_note "errpt -a -s failed (rc=$_erc, ${_ecnt:-unknown number of} entries in the window); falling back to full 'errpt -a' capped at $ERRPT_MAX_LINES lines"
        run_cmd -t 300 -p "$_ecap_p" errpt_full_capped
      fi
    fi
  else
    info_note "errpt -s date window: system clock ($START_TIME) outside 1971..2037; running full 'errpt -a' capped at $ERRPT_MAX_LINES lines"
    run_cmd -t 300 -p "$_ecap_p" errpt_full_capped
  fi
else
  run_cmd -t 300 "errpt -a"
fi
chk_space
run_cmd -p "# errpt summary: top 20 IDENTIFIER / T / C / RESOURCE_NAME (since ${ERRPT_START:-start of error log})" errpt_top
if [ -x "$ERRDEMON" ]; then
  run_cmd -i -p "/usr/lib/errdemon -l" "$ERRDEMON -l"
fi
run_cmd -i "alog -o -t console"

#============================== 03. Disks & Bootlist ==========================
sec "03. Disks & Bootlist"
run_save lsdev_disk "lsdev -Cc disk"
run_save lspv_out "lspv"

need lsdev_disk "per-disk lsattr / disk summary" || :
DISK_LIST=$(devs lsdev_disk hdisk)
DISK_CNT=$(echo "$DISK_LIST" | awk 'NF {c += NF} END {print c + 0}')
ROOTVG_DISKS=""
if need lspv_out "rootvg sample disk selection / VG column of the disk summary"; then
  ROOTVG_DISKS=$(awk '$3 == "rootvg" && $1 ~ /^hdisk[0-9]+$/ {print $1}' "$TMPD/lspv_out" 2>/dev/null)
fi

if [ "$ALL_DISKS" -eq 1 ] || [ "$DISK_CNT" -le 10 ]; then
  for _d in $DISK_LIST; do
    run_cmd "lsattr -El $_d"
  done
else
  run_cmd -t $((CMD_TIMEOUT * 3)) \
    -p "# lsattr -El hdisk* (All $DISK_CNT Available disks key attributes summary)" disk_summary
  _first_root=$(echo "$ROOTVG_DISKS" | awk 'NF {print $1; exit}')
  SAMPLE_DISKS=$( { echo "$_first_root"; awk '!seen[$2]++ {print $1}' "$TMPD/disk_pcm" 2>/dev/null; } |
    awk '$1 ~ /^hdisk[0-9]+$/ && !seen[$1]++ {print $1}')
  [ -n "$SAMPLE_DISKS" ] || SAMPLE_DISKS=$(echo "$DISK_LIST" | awk 'NF {print $1; exit}')
  for _d in $SAMPLE_DISKS; do
    run_cmd "lsattr -El $_d"
  done
fi

run_cmd -i "bootlist -m normal -o"
run_cmd -i "getconf BOOT_DEVICE"
lvm_q lslv -m hd5

#============================== 04. Adapters, Multipath & FC ==================
sec "04. Adapters, Multipath & FC"
run_save lsdev_adapter "lsdev -Cc adapter"
need lsdev_adapter "fcs / vscsi / sissas / EtherChannel checks" || :
run_save lspath_out -i "lspath"
run_cmd -i "lspath | grep -vw Enabled"
if usable lspath_out && awk '$1 != "Enabled" {f=1; exit} END {exit !f}' "$TMPD/lspath_out" 2>/dev/null; then
  run_cmd -i 'lspath -F "status:name:path_id:parent:connection" | grep -v "^Enabled:"'
fi

if have lsmpio; then
  run_cmd -i "lsmpio"
  run_cmd -i "lsmpio -are"
fi

if have pcmpath; then
  run_cmd -i "pcmpath query adapter"
  run_cmd -i -t 180 "pcmpath query device"
fi

if have powermt; then
  run_cmd -i "powermt display"
  run_cmd -i -t 120 "powermt display dev=all"
fi

if have dlnkmgr; then
  run_cmd -i "dlnkmgr view -sys"
  run_cmd -i -t 120 "dlnkmgr view -path"
  run_cmd -i -t 120 "dlnkmgr view -lu"
fi

need lsdev_all "fscsi lsattr" || :
for _fscsi in $(devs lsdev_all fscsi); do
  run_save "fscsi_$_fscsi" "lsattr -El $_fscsi"
done

FC_LINKED=""; FC_IN_LSPATH=""; FC_NPIV_UP=""
if usable lspath_out; then
  FC_LINKED=$(awk '$1 == "Enabled" && $3 ~ /^fscsi[0-9]+$/ && !seen[$3]++ {printf "%s ", $3}' \
    "$TMPD/lspath_out" 2>/dev/null)
fi
LSPATH_READ=0
case $(sed -n 2p "$TMPD/lspath_out.meta" 2>/dev/null) in
  124|125|127|"") ;;
  *) LSPATH_READ=1
     FC_IN_LSPATH=$(awk '$3 ~ /^fscsi[0-9]+$/ && !seen[$3]++ {printf "%s ", $3}' \
       "$TMPD/lspath_out" 2>/dev/null) ;;
esac
if usable lsnports_out; then
  FC_NPIV_UP=$(awk '$1 ~ /^fcs[0-9]+$/ && $3 == "1" {printf "%s ", $1}' "$TMPD/lsnports_out" 2>/dev/null)
fi

for _fcs in $(devs lsdev_adapter fcs); do
  _fscsi=""
  if usable lsdev_parent; then
    _fscsi=$(awk -F: -v p="$_fcs" '
      $1 ~ /^fscsi[0-9]+$/ && $2 == "Available" && $3 == p {print $1; exit}' "$TMPD/lsdev_parent" 2>/dev/null)
  fi
  if [ -z "$_fscsi" ] && usable lsdev_all; then
    _fscsi=$(awk -v f="$_fcs" '
      $1 == f && $3 ~ /^[0-9A-Za-z-]+$/ { loc = $3 "-01" }
      $1 ~ /^fscsi[0-9]+$/ && $2 == "Available" { by_loc[$3] = $1 }
      END { if (loc != "" && (loc in by_loc)) print by_loc[loc] }' "$TMPD/lsdev_all" 2>/dev/null)
  fi
  _attach=""; _scsi_id=""
  if [ -n "$_fscsi" ] && usable "fscsi_$_fscsi"; then
    _attach=$(awk '$1 == "attach" {print $2; exit}' "$TMPD/fscsi_$_fscsi" 2>/dev/null)
    _scsi_id=$(awk '$1 == "scsi_id" && $2 ~ /^0x[0-9A-Fa-f]+$/ {print $2; exit}' "$TMPD/fscsi_$_fscsi" 2>/dev/null)
  fi
  _non_mpio_up=0; _inf_why=""
  if [ -n "$_fscsi" ] && [ -n "$_attach" ] && [ "$_attach" != "none" ] && [ -n "$_scsi_id" ] && usable lsdev_parent; then
    if awk -F: -v p="$_fscsi" '
      $3 == p && $2 == "Available" && $1 ~ /^(rmt|smc)[0-9]+$/ {f=1; exit}
      END {exit !f}' "$TMPD/lsdev_parent" 2>/dev/null; then
      _non_mpio_up=1; _inf_why="Available tape/changer under $_fscsi"
    elif in_words "$_fscsi" "$FC_IN_LSPATH"; then
      :
    elif [ "$LSPATH_READ" -eq 1 ] && awk -F: -v p="$_fscsi" '
      $3 == p && $2 == "Available" && $1 ~ /^hdisk[0-9]+$/ {f=1; exit}
      END {exit !f}' "$TMPD/lsdev_parent" 2>/dev/null; then
      _non_mpio_up=1; _inf_why="Available non-MPIO hdisk under $_fscsi (no lspath entry)"
    fi
  fi
  if [ -n "$_fscsi" ] && in_words "$_fscsi" "$FC_LINKED"; then
    run_cmd -i -t 60 "fcstat $_fcs"
  elif in_words "$_fcs" "$FC_NPIV_UP"; then
    run_cmd -i -t 60 "fcstat $_fcs"
  elif [ "$_non_mpio_up" -eq 1 ]; then
    info_note "fcstat $_fcs: link inferred ($_inf_why, attach=$_attach, scsi_id=$_scsi_id), 30s timeout"
    run_cmd -i -t 30 "fcstat $_fcs"
  else
    if usable lspath_out; then
      if [ -n "$_fscsi" ]; then
        _why="no Enabled path via $_fscsi in lspath${_attach:+ (attach=$_attach)}"
      else
        _why="fscsi child not found, link state unknown"
      fi
    else
      _why="lspath output unavailable, link state unknown"
    fi
    if [ $IS_VIOS -eq 1 ]; then
      if usable lsnports_out; then
        _why="$_why; not fabric=1 in lsnports"
      else
        _why="$_why; lsnports output unavailable"
      fi
    fi
    skip_note "fcstat $_fcs: $_why"
  fi
  run_cmd "lsattr -El $_fcs"
done

for _vscsi in $(devs lsdev_adapter vscsi); do
  run_cmd "lsattr -El $_vscsi"
done

if have sissasraidmgr; then
  for _sas in $(devs lsdev_adapter sissas); do
    run_cmd -i "sissasraidmgr -L -j1 -l $_sas"
    run_cmd -i "sissasraidmgr -M -l $_sas -o0"
  done
fi

#============================== 05. LVM & Filesystems =========================
sec "05. LVM & Filesystems"
replay lspv_out "lspv"
run_cmd "lsvg"

ACTIVE_VGS=""
run_save lsvg_on -i "lsvg -L -o"
_vrc=$?
if [ $_vrc -ne 0 ] && [ $_vrc -ne 124 ] && [ $_vrc -ne 125 ] && [ $_vrc -ne 127 ]; then
  run_save lsvg_on "lsvg -o"
  _vrc=$?
fi
if [ $_vrc -eq 0 ]; then
  ACTIVE_VGS=$(awk '$1 ~ /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/ {print $1}' "$TMPD/lsvg_on" 2>/dev/null)
elif [ $_vrc -ne 124 ] && [ $_vrc -ne 125 ]; then
  skip_note "per-VG checks: \"lsvg -o\" failed (rc=$_vrc)"
fi
for _vg in $ACTIVE_VGS; do
  lvm_q lsvg "$_vg"
  lvm_q lsvg -l "$_vg"
  lvm_q lsvg -p "$_vg"
done

# Run df only on local jfs/jfs2 filesystems to prevent hanging on unresponsive NFS mounts
run_save mount_out "mount"
if need mount_out "df on local jfs/jfs2"; then
  _fsre='^/[-A-Za-z0-9_./+@,:%]*$'
  LOCAL_FS=$(awk -v re="$_fsre" '($3 == "jfs" || $3 == "jfs2") && $2 ~ re {printf "%s ", $2}' "$TMPD/mount_out" 2>/dev/null)
  LOCAL_FS=${LOCAL_FS% }
  for _mp in $(awk -v re="$_fsre" '($3 == "jfs" || $3 == "jfs2") && $2 !~ re {print $2}' "$TMPD/mount_out" 2>/dev/null); do
    skip_note "df: unusual mount point $_mp"
  done
  if [ -n "$LOCAL_FS" ]; then
    run_cmd -t 60 "df -g $LOCAL_FS"
  else
    skip_note "df: no local jfs/jfs2 file system found in mount output"
  fi
fi

run_save lsfs_c "lsfs -c"
if usable mount_out && need lsfs_c "lsfs -c vs mount AutoMount check"; then
  run_cmd -p "# lsfs -c vs mount: AutoMount filesystems that are not mounted now" fs_automount_check
fi

#============================== 06. Network ===================================
sec "06. Network"
run_cmd "netstat -in"
run_cmd "netstat -rn"
run_cmd "lsattr -El inet0"
run_cmd "ifconfig -a"
run_cmd -p "cat /etc/hosts" cat_hosts_safe

NET_AGG_LIST=""
ETHCH_LIST=""
if usable lsdev_adapter; then
  NET_AGG_LIST=$(awk '$1 ~ /^ent[0-9]+$/ && $2 == "Available" && /EtherChannel|802\.3ad|Shared Ethernet Adapter/ {print $1}' \
    "$TMPD/lsdev_adapter" 2>/dev/null)
  ETHCH_LIST=$(awk '$1 ~ /^ent[0-9]+$/ && $2 == "Available" && /EtherChannel|802\.3ad/ {print $1}' \
    "$TMPD/lsdev_adapter" 2>/dev/null)
fi
for _ent in $NET_AGG_LIST; do
  run_cmd "lsattr -El $_ent"
done
# Read-only ODM attributes for ordinary LPAR Virtual I/O Ethernet adapters (PIQS mtu_bypass / min_buf_* / max_buf_*).
# Never run entstat (-d/-r) on non-EtherChannel adapters.
VIO_ENT_LIST=""
if usable lsdev_adapter; then
  VIO_ENT_LIST=$(awk '
    $1 ~ /^ent[0-9]+$/ && $2 == "Available" &&
    !/EtherChannel|802\.3ad|Shared Ethernet Adapter/ &&
    (/Virtual I\/O Ethernet/ || /Virtual Ethernet/ || /l-lan/ || /Virtual NIC/ || /vNIC/) {
      if (!seen[$1]++) print $1
    }' "$TMPD/lsdev_adapter" 2>/dev/null)
fi
_vio_ent_cnt=0
for _ent in $VIO_ENT_LIST; do
  case "$_ent" in
    ent[0-9]*) ;;
    *) continue ;;
  esac
  _vio_ent_cnt=$((_vio_ent_cnt + 1))
  if [ "$_vio_ent_cnt" -gt 32 ]; then
    info_note "Virtual I/O Ethernet lsattr capped at 32 adapters"
    break
  fi
  run_cmd "lsattr -El $_ent"
done
if [ -n "$ETHCH_LIST" ]; then
  for _ent in $ETHCH_LIST; do
    run_cmd -i -t 60 "entstat $_ent"
  done
elif usable lsdev_adapter; then
  skip_note "entstat: no Available EtherChannel adapter in 'lsdev -Cc adapter'"
else
  skip_note "entstat / EtherChannel / SEA lsattr: 'lsdev -Cc adapter' output unusable"
fi

#============================== 07. Resources & Tuning ========================
sec "07. Resources & Tuning"
run_cmd "vmstat 1 3"
run_cmd "vmstat -v"
run_cmd "svmon -G"
run_cmd "lsps -s"
run_cmd "lsps -a"
run_cmd "iostat 1 3"
if have lparstat; then
  run_cmd -i "lparstat 1 3"
fi
run_cmd "vmo -a"
run_cmd -i -t 60 "no -a"
run_cmd -i -t 60 "ioo -a"
run_cmd -i -t 60 "schedo -a"
run_cmd -i -p "ulimit -a" ulimit_safe
run_cmd -i -p "cat /etc/security/limits (resource limit stanzas only)" security_limits_safe

#============================== 08. Uptime, Processes & Cron ==================
sec "08. Uptime, Processes & Cron"
run_cmd "uptime"
run_cmd -R -p "ps -eo pid (process count)" ps_ef_cnt
run_cmd -R -p "ps -eo user,pid,ppid,pcpu,pmem,vsz,tty,time,comm | sort -rn -k 4,4 | head -n 10" ps_top_cpu
run_cmd -R -p "ps -eo user,pid,ppid,pcpu,pmem,vsz,tty,time,comm | sort -rn -k 5,5 | head -n 10" ps_top_mem
run_cmd -R -p "ps -eo user,pid,ppid,pcpu,pmem,vsz,tty,time,comm (comm only, args omitted)" ps_ef_out
run_cmd -i -R -p "crontab -l (schedule & executable basename only; env/comments/args omitted)" crontab_safe
run_cmd "lssrc -a"
run_cmd -i "lssrc -ls xntpd"

#============================== 09. System Dump ===============================
sec "09. System Dump"
run_cmd -i "sysdumpdev -e"
run_cmd "sysdumpdev -l"
run_cmd -i "sysdumpdev -L"
if [ -x "$DUMPCHECK" ]; then
  run_cmd -i -p "/usr/lib/ras/dumpcheck -p" "$DUMPCHECK -p"
fi

#============================== 10. PowerHA Cluster ===========================
sec "10. PowerHA Cluster"
run_cmd -i "lssrc -g cluster"
if [ $IS_HA -eq 1 ]; then
  run_cmd -i "lslpp -l 'cluster.*'"
fi

if [ -x "$CLSHOWSRV" ]; then
  run_cmd -i "lssrc -ls clstrmgrES | grep -i state"
  run_cmd -i -t 120 -p "/usr/es/sbin/cluster/utilities/clshowsrv -v" "$CLSHOWSRV -v"
fi
if [ -x "$CLMGR" ]; then
  run_cmd -i -t 120 -p "/usr/es/sbin/cluster/utilities/clmgr query cluster" "$CLMGR query cluster"
fi
if [ -x "$CLTOPINFO" ]; then
  run_cmd -i -t 120 -p "/usr/es/sbin/cluster/utilities/cltopinfo" "$CLTOPINFO"
fi
if [ -x "$CLRGINFO" ]; then
  run_cmd -i -t 120 -p "/usr/es/sbin/cluster/utilities/clRGinfo" "$CLRGINFO"
fi
if have lscluster && usable lspv_out && awk '$3 == "caavg_private" {f=1} END {exit !f}' "$TMPD/lspv_out" 2>/dev/null; then
  run_cmd -i "lscluster -c"
  run_cmd -i "lscluster -m"
  run_cmd -i "lscluster -i"
  run_cmd -i "lscluster -d"
fi
if [ -x "$MMGETSTATE" ]; then
  run_cmd -i -t 60 -p "/usr/lpp/mmfs/bin/mmgetstate -a" "$MMGETSTATE -a"
  run_cmd -i -t 60 -p "/usr/lpp/mmfs/bin/mmlsmount all -L" "$MMLSMOUNT all -L"
fi

#============================== 11. Hardware VPD & Microcode ==================
sec "11. Hardware VPD & Microcode"
run_cmd -t 300 "lscfg -vp"
run_cmd -i -t 120 "lsmcode -c"

#============================== Log Trailer & Manifest ========================
TIMEOUT_CNT=$TO_TOTAL
FINISH_TIME=$(date '+%Y-%m-%d %H:%M:%S')
FINISH_TIME_RAW=$(iso_now_raw)
TOTAL_DUR_SEC=$(( ${SECONDS%.*} - START_SEC ))
[ "$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 ] || [ "$TIMEOUT_CNT" -gt 0 ] || [ "$SKIP_CNT" -gt 0 ] || [ "$CNT_FAILED" -gt 0 ]; then
  COLLECTION_STATUS="partial"
else
  COLLECTION_STATUS="complete"
fi

_j_schema=$(printf '%s' "$SCHEMA_VERSION" | json_escape)
_j_sname=$(printf '%s' "$SCRIPT_NAME" | json_escape)
_j_sver=$(printf '%s' "$VERSION" | json_escape)
_j_sfile=$(printf '%s' "$SCRIPT_FILE" | json_escape)
_j_ssha=$(printf '%s' "$SCRIPT_SELF_SHA256" | json_escape)
_j_st_raw=$(printf '%s' "$START_TIME_RAW" | json_escape)
_j_fn_raw=$(printf '%s' "$FINISH_TIME_RAW" | json_escape)
_j_tz=$(printf '%s' "$TZ_RAW" | json_escape)
_j_date=$(printf '%s' "$DATE_RAW" | json_escape)
_j_user=$(printf '%s' "$RUN_AS_USER" | json_escape)
_j_priv=$(printf '%s' "$PRIVILEGE_MODE" | json_escape)
_j_cstat=$(printf '%s' "$COLLECTION_STATUS" | json_escape)
_j_host=$(printf '%s' "$HOST" | json_escape)
_j_sn=$(printf '%s' "$MACH_SN" | json_escape)
_j_os=$(printf '%s' "$OS_LEVEL_STR" | json_escape)
_j_mach=$(printf '%s' "$MACH_INFO" | json_escape)
_j_vios=$(printf '%s' "$VIOS_LEVEL_STR" | json_escape)

{
  printf '\n================================================================================\n'
  printf 'TIMEOUT_COUNT           : %s\n' "$TIMEOUT_CNT"
  printf 'SKIPPED_COUNT           : %s\n' "$SKIP_CNT"
  printf 'ERROR_COUNT             : %s\n' "$ERR_CNT"
  printf 'PERMISSION_DENIED_COUNT : %s\n' "$CNT_PERM"
  printf 'COMMAND_MISSING_COUNT   : %s\n' "$CNT_MISSING"
  printf 'REDACTED_ITEM_COUNT     : %s\n' "$CNT_REDACTED"
  printf 'COLLECTION_STATUS       : %s\n' "$COLLECTION_STATUS"
  printf 'FINISHED_AT_RAW         : %s\n' "$FINISH_TIME_RAW"
  printf 'END OF AIX CHECK LOG : %s  (Finished at %s)\n' "$HOST" "$FINISH_TIME"
  printf '================================================================================\n'
  printf 'BEGIN CHECK MANIFEST JSON\n'
  printf '{\n'
  printf '  "schema": %s,\n' "$_j_schema"
  printf '  "collector": {\n'
  printf '    "name": %s,\n' "$_j_sname"
  printf '    "version": %s,\n' "$_j_sver"
  printf '    "script": %s,\n' "$_j_sfile"
  printf '    "script_sha256": %s,\n' "$_j_ssha"
  printf '    "platform": "aix"\n'
  printf '  },\n'
  printf '  "collection": {\n'
  printf '    "started_at_raw": %s,\n' "$_j_st_raw"
  printf '    "finished_at_raw": %s,\n' "$_j_fn_raw"
  printf '    "timezone_raw": %s,\n' "$_j_tz"
  printf '    "date_raw": %s,\n' "$_j_date"
  printf '    "duration_sec": %s,\n' "$TOTAL_DUR_SEC"
  printf '    "run_as_user": %s,\n' "$_j_user"
  printf '    "run_as_uid": %s,\n' "$RUN_AS_UID"
  printf '    "is_root": %s,\n' "$IS_ROOT"
  printf '    "privilege_mode": %s,\n' "$_j_priv"
  printf '    "command_timeout_sec": %s,\n' "$CMD_TIMEOUT"
  printf '    "global_timeout_sec": %s,\n' "$GLOBAL_TIMEOUT"
  printf '    "status": %s,\n' "$_j_cstat"
  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_TO_ITEM"
  printf '      "failed": %s,\n' "$CNT_FAILED"
  printf '      "not_applicable": %s,\n' "$CNT_NA"
  printf '      "skipped": %s,\n' "$CNT_SKIP_ITEM"
  printf '      "redacted": %s\n' "$CNT_REDACTED"
  printf '    }\n'
  printf '  },\n'
  printf '  "host": {\n'
  printf '    "hostname": %s,\n' "$_j_host"
  printf '    "serial": %s,\n' "$_j_sn"
  printf '    "os_level": %s,\n' "$_j_os"
  printf '    "machine": %s,\n' "$_j_mach"
  printf '    "vios_level": %s\n' "$_j_vios"
  printf '  },\n'
  printf '  "redaction": {\n'
  printf '    "applied": true,\n'
  printf '    "mode": "collector_default",\n'
  printf '    "rules": [\n'
  printf '      "security_passwd_shadow_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
  if [ -n "$PRIV_WARN" ]; then
    printf '%s' "$(printf '%s' "$PRIV_WARN" | json_escape)"
    _wf=0
  fi
  if [ -n "$CLOCK_WARN" ]; then
    [ "$_wf" -eq 0 ] && printf ', '
    printf '%s' "$(printf '%s' "$CLOCK_WARN" | json_escape)"
    _wf=0
  fi
  printf '],\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 < "$TMPD/items.jsonl"
  printf '\n  ]\n'
  printf '}\n'
  printf 'END CHECK MANIFEST JSON\n'
} >> "$LOG"

if [ ! -s "$LOG" ]; then
  echo "ERROR: failed to write check log $LOG" >&2
  exit 1
fi

if [ $STDOUT_MODE -eq 1 ]; then
  cat "$LOG"
else
  echo "[$SCRIPT_FILE] Done. Output saved to: $LOG"
  if [ -n "$PRIV_WARN" ]; then
    echo "[$SCRIPT_FILE] WARNING: $PRIV_WARN."
  fi
  if [ -n "$CLOCK_WARN" ]; then
    echo "[$SCRIPT_FILE] WARNING: $CLOCK_WARN."
  fi
  if [ "$TIMEOUT_CNT" -gt 0 ]; then
    echo "[$SCRIPT_FILE] WARNING: $TIMEOUT_CNT command(s) timed out, search '*** TIMEOUT' in the log."
  fi
  if [ "$SKIP_CNT" -gt 0 ]; then
    echo "[$SCRIPT_FILE] WARNING: $SKIP_CNT command(s) skipped (circuit breaker / -T deadline / low disk space), search '*** SKIPPED' in the log."
  fi
  if [ "$ERR_CNT" -gt 0 ]; then
    echo "[$SCRIPT_FILE] WARNING: $ERR_CNT core command(s) returned non-zero status (see ERROR_COUNT and '#@ rc=' in the log; exit 3 for this only with -E)."
  fi
fi
if [ "$TIMEOUT_CNT" -gt 0 ] || [ "$SKIP_CNT" -gt 0 ]; then
  exit 3
fi
if [ "$ERR_EXIT" -eq 1 ] && [ "$ERR_CNT" -gt 0 ]; then
  exit 3
fi
exit 0
