#!/bin/bash

# Clear the IPMI System Event Log at the very start so any events generated
# during this script run are fresh. The SEL is read and displayed later;
# clearing first avoids showing stale events from previous boots.
ipmicfg -clrint 2>/dev/null

# -- Firmware Version Tables --------------------------------------------------
# Update these when new BIOS or IPMI firmware is released.
# Format: Board=Version  (must match dmidecode "Product Name" last field exactly)
declare -A BIOS_LATEST=(
    [H12SSW-AN6]="3.5"
    [X10DDW-i]="3.4"
    [X10DRH-CT]="3.4a"
    [X10DRi]="3.4a"
    [X10DRi-T]="3.4a"
    [X10SLM-F]="3.4"
    [X10SRi-F]="3.4"
    [X11DDW-NT]="4.6"
    [X11DPH-T]="4.7"
    [X11DPU]="4.3"
    [X11SCH-F]="2.8"
    [X11SSH-F]="3.5"
    [X11SSL-CF]="3.6"
    [X12DDW-A6]="2.5"
    [X12STH-SYS]="2.3"
    [X12STW-TF]="2.2"
    [X13DDW-A]="01.03.20"
)
declare -A IPMI_LATEST=(
    [H12SSW-AN6]="01.06.28"
    [X10DDW-i]="3.91.00"
    [X10DRH-CT]="3.94.00"
    [X10DRi]="3.91.00"
    [X10DRi-T]="3.91.00"
    [X10SLM-F]="3.88.00"
    [X10SRi-F]="3.93.00"
    [X11DDW-NT]="01.74.17"
    [X11DPH-T]="01.74.19"
    [X11DPU]="01.74.14"
    [X11SCH-F]="01.74.19"
    [X11SSH-F]="1.74.00"
    [X11SSL-CF]="1.78.00"
    [X12DDW-A6]="01.08.02"
    [X12STH-SYS]="01.06.14"
    [X12STW-TF]="01.08.08"
    [X13DDW-A]="01.03.20"
)

# -- Section Toggles ----------------------------------------------------------
# Set to 1 to skip that section entirely
SKIP_TOOL_INSTALL=0      # SST / IPMICFG / STORCLI installation
SKIP_SST_FW_UPDATE=0     # Intel SSD firmware update via SST
SKIP_SERVER_SUMMARY=0    # SERVER SUMMARY box
SKIP_TOOL_BOX=0          # TOOL INSTALLATION result box
SKIP_STORAGE=0           # STORAGE box (RAID/drive details)
SKIP_SMART_PER_DISK=0    # Per-disk SMART box (non-RAID only)
SKIP_PSU_CHECK=0         # PSU status via ipmicfg
SKIP_NVME_HEALTH=0       # NVMe smart-log health table
SKIP_BOND_CHECK=0        # Bond interface member health
SKIP_LSPCI=0             # PCI device summary
SKIP_SEL=0               # SEL event log

# -- Thresholds ---------------------------------------------------------------
# Number of PSUs expected in this server (mismatch triggers a warning)
PSU_EXPECTED_COUNT=2
# NVMe percentage used at or above this value = FAIL
NVME_PCT_USED_FAIL=90
# NVMe available spare below this value = WARN
NVME_SPARE_WARN=10
# RAID FW manifest URL
RAID_FW_URL="http://216.104.40.250/raid/raid_versions"

# -- Colors -------------------------------------------------------------------
R=$'\033[1;31m'
G=$'\033[1;32m'
Y=$'\033[1;33m'
C=$'\033[1;36m'
B=$'\033[1;34m'
M=$'\033[1;35m'
DIM=$'\033[0;37m'
GRAY=$'\033[1;90m'
RST=$'\033[0m'
BOLD=$'\033[1m'
BGR=$'\033[41m'
BGG=$'\033[42m'
BGY=$'\033[43m'
BLK=$'\033[0;30m'

# -- Box drawing --------------------------------------------------------------
W=74
INNER=74

rep() {
    local i out=''
    for (( i=0; i<$2; i++ )); do out+="$1"; done
    printf '%s' "$out"
}

_TL() { printf '\xe2\x95\x94'; }
_EQ() { printf '\xe2\x95\x90'; }
_TR() { printf '\xe2\x95\x97'; }
_ML() { printf '\xe2\x95\xa0'; }
_MR() { printf '\xe2\x95\xa3'; }
_VB() { printf '\xe2\x95\x91'; }
_BL() { printf '\xe2\x95\x9a'; }
_BR() { printf '\xe2\x95\x9d'; }
_HD() { printf '\xe2\x94\x80'; }

hline()   { rep "$(_EQ)" $W; }
divline() { rep "$(_HD)" $INNER; }

_BOX_COLOR="$C"

box_open() {
    local title="$1" color="${2:-$C}"
    _BOX_COLOR="$color"
    local tlen=${#title}
    local lpad=$(( (W - tlen - 2) / 2 ))
    local rpad=$(( W - tlen - 2 - lpad ))
    printf '\n'
    printf "%b%s%s%s%b\n"  "$color" "$(_TL)" "$(hline)" "$(_TR)" "$RST"
    printf "%b%s%s%b%b%b %s %b%b%s%s%b\n" "$color" "$(_VB)" "$(rep ' ' $lpad)" "$RST" "$BOLD" "$Y" "$title" "$RST" "$color" "$(rep ' ' $rpad)" "$(_VB)" "$RST"
    printf "%b%s%s%s%b\n"  "$color" "$(_ML)" "$(hline)" "$(_MR)" "$RST"
}

box_close() {
    local color="${1:-$_BOX_COLOR}"
    printf "%b%s%s%s%b\n"  "$color" "$(_BL)" "$(hline)" "$(_BR)" "$RST"
}

bline() {
    local text="$1" bc="${2:-$_BOX_COLOR}"
    local vis
    vis=$(printf '%s' "$text" | sed -E 's/\x1b\[[0-9;:]*[mGKHFJA-Za-z]//g; s/\x1b\([A-Z]//g')
    local pad=$(( INNER - ${#vis} ))
    [ "$pad" -lt 0 ] && pad=0
    printf "%b%s%b%s%s%b%s%b\n" "$bc" "$(_VB)" "$RST" "$text" "$(rep ' ' $pad)" "$bc" "$(_VB)" "$RST"
}

bempty()   { bline '' "${1:-$_BOX_COLOR}"; }
bdivider() { bline "$(printf "  %b%s%b" "$DIM" "$(rep "$(_HD)" 70)" "$RST")" "${1:-$_BOX_COLOR}"; }

bkv() {
    local key="$1" val="$2" lc="${3:-$G}" vc="${4:-$RST}" bc="${5:-$_BOX_COLOR}"
    bline "$(printf "  %b%-22s%b%b%s%b" "$lc" "$key" "$RST" "$vc" "$val" "$RST")" "$bc"
}

# print_smart_attrs SMART_OUTPUT IS_SSD
print_smart_attrs() {
    local smart_out="$1" is_ssd="$2"
    bline "$(printf "    %b%-20s%b" "$G" "SMART Attributes:" "$RST")"
    while read -r id attr f v w t tp up wf raw; do
        case "$attr" in
            Current_Pending_Sector|Power_On_Hours|Reallocated_Sector_Ct|Offline_Uncorrectable)
                if { [ "$v" -lt "$t" ] 2>/dev/null; } || \
                   { [ "$raw" -gt 0 ] 2>/dev/null && echo "$attr" | grep -qE "Reallocated|Pending|Offline"; }; then
                    bline "$(printf "      %b%s: %s%b" "$R"   "$attr" "$raw" "$RST")"
                else
                    bline "$(printf "      %b%s: %s%b" "$DIM" "$attr" "$raw" "$RST")"
                fi ;;
            Reported_Uncorrect|UDMA_CRC_Error_Count)
                if [ "$raw" -gt 0 ] 2>/dev/null; then
                    bline "$(printf "      %b%s: %s%b" "$R"   "$attr" "$raw" "$RST")"
                else
                    bline "$(printf "      %b%s: %s%b" "$DIM" "$attr" "$raw" "$RST")"
                fi ;;
            Total_LBAs_Written)
                [ "$is_ssd" -gt 0 ] 2>/dev/null && \
                    bline "$(printf "      %b%s: %s%b" "$DIM" "$attr" "$raw" "$RST")" ;;
            Media_Wearout_Indicator|Wear_Leveling_Count)
                if [ "$is_ssd" -gt 0 ] 2>/dev/null; then
                    local wcolor="$G"
                    [ "$v" -lt 80 ] 2>/dev/null && wcolor="$Y"
                    [ "$v" -lt 50 ] 2>/dev/null && wcolor="$R"
                    bline "$(printf "      %b%s: %s%b" "$wcolor" "$attr" "$v" "$RST")"
                fi ;;
        esac
    done < <(printf '%s' "$smart_out" | grep -E "Current_Pending|Power_On_Hours|Reallocated_Sector|Offline_Unco|Media_Wearout|Wear_Leveling|Reported_Uncorrect|UDMA_CRC_Error|Total_LBAs_Written")
}

# drive_entry LABEL [SMARTCTL_ARGS...]
drive_entry() {
    local label="$1"; shift
    local smart_out model serial size fw
    smart_out=$(smartctl "$@" 2>/dev/null)
    model=$(printf '%s' "$smart_out"  | grep -E "Device Model|Model Number"  | head -1 | cut -d: -f2 | xargs)
    serial=$(printf '%s' "$smart_out" | grep "Serial Number"                 | head -1 | cut -d: -f2 | xargs)
    fw=$(printf '%s' "$smart_out"     | grep "Firmware Version"              | head -1 | cut -d: -f2 | xargs)
    # Use lsblk --bytes for exact size, then format to 2 decimal places.
    # lsblk default uses binary 1024-based units which shows 7T instead of 7.68TB.
    # smartctl User Capacity on NVMe returns wrong values (namespace metadata size).
    _size_bytes=$(lsblk -bdno SIZE "$label" 2>/dev/null | head -1)
    if [ -n "$_size_bytes" ] && [ "$_size_bytes" -gt 0 ] 2>/dev/null; then
        size=$(awk -v b="$_size_bytes" 'BEGIN{
            if      (b>=1000000000000) printf "%.2f TB", b/1000000000000
            else if (b>=1000000000)    printf "%.2f GB", b/1000000000
            else if (b>=1000000)       printf "%.2f MB", b/1000000
            else                       printf "%d B",    b
        }')
    else
        # Fall back to smartctl User Capacity
        size=$(printf '%s' "$smart_out" | grep "User Capacity" | head -1 | cut -d'[' -f2 | cut -d']' -f1 | xargs)
    fi
    unset _size_bytes
    local is_ssd=0 disk_type="HDD"
    if printf '%s' "$smart_out" | grep -qi "NVM Express\|nvme"; then
        disk_type="NVMe"; is_ssd=1
    elif printf '%s' "$smart_out" | grep -qi "Solid State\|Rotation Rate.*Solid"; then
        disk_type="SSD"; is_ssd=1
    elif ! printf '%s' "$smart_out" | grep -q "Rotation Rate"; then
        disk_type="SSD"; is_ssd=1
    fi
    local sst_badge
    sst_badge=$(sst_badge_for "$serial")
    bline "$(printf "  %b%b%s%b  %b[Non-RAID]%b" "$BOLD" "$C" "$label" "$RST" "$DIM" "$RST")"
    bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Type:"     "$RST" "$Y"   "$disk_type"           "$RST")"
    bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Model:"    "$RST" "$Y"   "${model:-(unknown)}"  "$RST")"
    bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Serial:"   "$RST" "$DIM" "${serial:-(unknown)}" "$RST")"
    bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Size:"     "$RST" "$C"   "${size:-(unknown)}"   "$RST")"
    bline "$(printf "    %b%-20s%b%b%s%b%s" "$G" "Firmware:" "$RST" "$C" "${fw:-(unknown)}" "$RST" "${sst_badge:+  $sst_badge}")"
    # For NVMe, supplement with nvme smart-log (richer health data)
    if [ "$disk_type" = "NVMe" ] && command -v nvme >/dev/null 2>&1; then
        local _ctrl="${1%n*}"   # /dev/nvme0n1 -> /dev/nvme0
        [ -e "$_ctrl" ] || _ctrl="$1"
        local _nvme_log
        _nvme_log=$(nvme smart-log "$_ctrl" 2>/dev/null)
        if [ -n "$_nvme_log" ]; then
            local _pct _spare _warn _temp
            _pct=$(printf '%s' "$_nvme_log" | awk -F: '/percentage_used/{gsub(/[^0-9]/,"",$2); print $2+0}')
            _spare=$(printf '%s' "$_nvme_log" | awk -F: '/available_spare[^_]/{gsub(/[^0-9]/,"",$2); print $2+0}')
            _warn=$(printf '%s' "$_nvme_log" | awk -F: '/critical_warning/{gsub(/[^0-9a-fx]/,"",$2); print $2}')
            _temp=$(printf '%s' "$_nvme_log" | awk -F: '/^temperature /{gsub(/[^0-9]/,"",$2); print $2+0}')
            bline "$(printf "    %b%-20s%b" "$G" "NVMe Health:" "$RST")"
            [ -n "$_pct" ]   && bline "$(printf "      %b%-22s%b%s%%" "$DIM" "Percentage Used:" "$RST" "$_pct")"
            [ -n "$_spare" ] && bline "$(printf "      %b%-22s%b%s%%" "$DIM" "Available Spare:" "$RST" "$_spare")"
            [ -n "$_temp" ]  && bline "$(printf "      %b%-22s%b%s C" "$DIM" "Temperature:" "$RST" "$_temp")"
            if [ -n "$_warn" ] && [ "$_warn" != "0x00" ] && [ "$_warn" != "0" ]; then
                bline "$(printf "      %b%-22s%b%b%s%b" "$R" "Critical Warning:" "$RST" "$R" "$_warn" "$RST")"
            else
                bline "$(printf "      %b%-22s%b%bOK%b" "$DIM" "Critical Warning:" "$RST" "$G" "$RST")"
            fi
        fi
    else
        print_smart_attrs "$smart_out" "$is_ssd"
    fi
    bempty
}


# =============================================================================
#  TOOL INSTALLATION -- SST / IPMICFG / STORCLI
# =============================================================================

if [ -f /etc/debian_version ]; then _OS="debian"
elif [ -f /etc/redhat-release ]; then _OS="rhel"
else _OS="unknown"; fi

if [ -r /etc/os-release ]; then
    . /etc/os-release
    _OS_PRETTY="${PRETTY_NAME:-}"
fi
[ -z "$_OS_PRETTY" ] && _OS_PRETTY="$_OS"

_TOOL_STATUSES=()

tool_state_token() {
    case "$1" in
        present)   printf '%b%binstalled%b'       "$BOLD" "$G" "$RST" ;;
        installed) printf '%b%bnewly installed%b'  "$BOLD" "$G" "$RST" ;;
        failed)    printf '%b%bFAILED%b'           "$BOLD" "$R" "$RST" ;;
    esac
}

# -- SST ----------------------------------------------------------------------
SST_URL="http://216.104.40.250/tools/sst"
if [ -f /usr/bin/sst ]; then
    _TOOL_STATUSES+=("SST=present")
else
    if [ "$_OS" = "debian" ]; then
        export DEBIAN_FRONTEND=noninteractive
        wget -q "${SST_URL}/sst-cli-linux-deb--2-3.zip" >/dev/null 2>&1 \
            && unzip -q sst-cli-linux-deb--2-3.zip >/dev/null 2>&1 \
            && dpkg -i sst_2.3.320-0_amd64.deb >/dev/null 2>&1
    elif [ "$_OS" = "rhel" ]; then
        wget -q "${SST_URL}/sst-cli-linux-rpm--2-3.zip" >/dev/null 2>&1 \
            && unzip -q sst-cli-linux-rpm--2-3.zip >/dev/null 2>&1 \
            && rpm -ivh sst-2.3.320-0.x86_64.rpm >/dev/null 2>&1
    fi
    [ -f /usr/bin/sst ] && _TOOL_STATUSES+=("SST=installed") || _TOOL_STATUSES+=("SST=failed")
fi

# -- IPMICFG ------------------------------------------------------------------
IPMI_URL="http://216.104.40.250/tools/ipmi"
IPMI_ZIP="IPMICFG_1.37.0_build.250723.zip"
IPMI_BINARY="/usr/src/IPMICFG_1.37.0_build.250723/Linux/64bit/IPMICFG-Linux.x86_64"
IPMI_SYMLINK="/usr/bin/ipmicfg"

if [ -f "$IPMI_SYMLINK" ] || [ -f /usr/local/bin/ipmicfg ]; then
    _TOOL_STATUSES+=("IPMICFG=present")
else
    wget -q -P /usr/src "${IPMI_URL}/${IPMI_ZIP}" >/dev/null 2>&1 \
        && unzip -q "/usr/src/${IPMI_ZIP}" -d /usr/src >/dev/null 2>&1 \
        && ln -s "$IPMI_BINARY" "$IPMI_SYMLINK" 2>/dev/null \
        && chmod +x "$IPMI_SYMLINK" 2>/dev/null
    [ -f "$IPMI_SYMLINK" ] && _TOOL_STATUSES+=("IPMICFG=installed") || _TOOL_STATUSES+=("IPMICFG=failed")
fi

# -- STORCLI ------------------------------------------------------------------
STOR_URL="http://184.154.112.130/raid/lsi/cli"
STOR_BINARY="/opt/MegaRAID/storcli/storcli64"
STOR_SYMLINK="/usr/bin/storcli"

if [ -f "$STOR_SYMLINK" ] || [ -f "$STOR_BINARY" ]; then
    _TOOL_STATUSES+=("STORCLI=present")
else
    if [ "$_OS" = "debian" ]; then
        PKG="storcli_007.1017.0000.0000_all.deb"
        wget -q "${STOR_URL}/${PKG}" -P /usr/src >/dev/null 2>&1 \
            && dpkg -i "/usr/src/${PKG}" >/dev/null 2>&1
    elif [ "$_OS" = "rhel" ]; then
        PKG="storcli-007.1017.0000.0000-1.noarch.rpm"
        wget -q "${STOR_URL}/${PKG}" -P /usr/src >/dev/null 2>&1 \
            && rpm -ivh "/usr/src/${PKG}" >/dev/null 2>&1
    fi
    if [ -f "$STOR_BINARY" ]; then
        cp "$STOR_BINARY" "$STOR_SYMLINK" >/dev/null 2>&1 && chmod +x "$STOR_SYMLINK"
        _TOOL_STATUSES+=("STORCLI=installed")
    else
        _TOOL_STATUSES+=("STORCLI=failed")
    fi
fi

# -- SST firmware scan + update -----------------------------------------------
# For each SSD/NVMe: check firmware currency and update if needed.
# Results stored in SST_STATUS_BY_SERIAL keyed by serial number.
declare -A SST_STATUS_BY_SERIAL
if command -v sst >/dev/null 2>&1; then
    sst set -system EnableLSIAdapter=true >/dev/null 2>&1
    _SST_DATA=$(sst show -ssd 2>/dev/null)

    while IFS="|" read -r idx path mdl serial fw status; do
        [ -z "$serial" ] && continue
        # Skip RAID virtual devices and HBA bus nodes
        if echo "$mdl"  | grep -qiE "^SMC[0-9]|^MegaRAID|^Avago|^Broadcom" \
        || echo "$path" | grep -qiE "^/dev/bus/"; then
            continue
        fi
        # Skip HDDs (NVMe and SSD paths must fall through)
        if echo "$path" | grep -qiE "^LSI[0-9]*$" \
        || echo "$mdl"  | grep -qiE "^(TOSHIBA|MG0[0-9]|ST[0-9]|HUS[0-9]|WD[0-9]|HGST|SEAGATE|HITACHI)"; then
            SST_STATUS_BY_SERIAL["$serial"]="HDD-SKIPPED"; continue
        fi
        if [ "$status" = "UP-TO-DATE" ]; then
            SST_STATUS_BY_SERIAL["$serial"]="UP-TO-DATE"
        elif [ "$status" = "UPDATE-AVAILABLE" ]; then
            sst load -f -ssd "$idx" >/dev/null 2>&1 \
                && SST_STATUS_BY_SERIAL["$serial"]="UPDATED" \
                || SST_STATUS_BY_SERIAL["$serial"]="FAILED"
        else
            SST_STATUS_BY_SERIAL["$serial"]="UNKNOWN"
        fi
    done < <(printf '%s' "$_SST_DATA" | awk '
        function flush() {
            if (f[1]!=""&&f[2]!="") print f[1]"|"f[2]"|"f[3]"|"f[4]"|"f[5]"|"f[6]
        }
        BEGIN { f[1]="";f[2]="";f[3]="";f[4]="";f[5]="";f[6]="" }
        /^- .* -$/             { flush(); f[1]="";f[2]="";f[3]="";f[4]="";f[5]="";f[6]="" }
        /^Index[ 	]*:/        { f[1]=$NF }
        /^DevicePath[ 	]*:/   { f[2]=$NF }
        /^ModelNumber[ 	]*:/  { f[3]=""; for(i=2;i<=NF;i++) if($i!=":") f[3]=f[3](f[3]!=""?" ":"")$i }
        /^SerialNumber[ 	]*:/ { f[4]=$NF }
        /^Firmware[ 	]*:/     { f[5]=$NF }
        /^FirmwareUpdateAvailable/ { f[6]=($0~/current firmware/)?"UP-TO-DATE":"UPDATE-AVAILABLE" }
        END { flush() }
    ')
fi

sst_badge_for() {
    local state="${SST_STATUS_BY_SERIAL[$1]}"
    [ -z "$state" ] && return
    case "$state" in
        UP-TO-DATE)  printf '%b%b  UP-TO-DATE  %b' "$BGG" "$BLK"  "$RST" ;;
        UPDATED)     printf '%b%b  UPDATED  %b'    "$BGG" "$BLK"  "$RST" ;;
        FAILED)      printf '%b%b  FW FAILED  %b'  "$BGR" "$BOLD" "$RST" ;;
        HDD-SKIPPED) printf '%b  HDD - NO FW  %b'  "$DIM"         "$RST" ;;
        UNKNOWN)     printf '%b  FW UNKNOWN  %b'   "$DIM"         "$RST" ;;
    esac
}

unset _OS _OS_PRETTY _SST_DATA


# =============================================================================
#  GATHER: lspci (once, reused for fan mode and lspci summary)
# =============================================================================
_LSPCI=$(lspci 2>/dev/null)


# =============================================================================
#  GATHER: PSU status from ipmicfg -sdr full
#  PSU sensors appear in SDR as "PS1 Status", "PS2 Status" etc.
#  Falls back to ipmicfg -summary if SDR has no PSU rows.
# =============================================================================
declare -a _PSU_ENTRIES=()
_PSU_DETECTED=0; _PSU_FAIL_COUNT=0
_SDR_FULL_PSU=$(ipmicfg -sdr full 2>/dev/null)
if [ "${SKIP_PSU_CHECK:-0}" != "1" ]; then
    # Extract PSU rows from SDR -- format: "OK | (ID) PS1 Status | type | reading |"
    _SDR_PSU=$(printf '%s' "$_SDR_FULL_PSU"         | grep -iE "PS[0-9]+[[:space:]]+Status|Power Supply[[:space:]]+[0-9]")

    if [ -n "$_SDR_PSU" ]; then
        while IFS= read -r _psu_line; do
            [ -z "$_psu_line" ] && continue
            _psu_stat=$(echo "$_psu_line" | awk -F'|' '{gsub(/^[ 	]+|[ 	]+$/,"",$1); print $1}')
            _psu_name=$(echo "$_psu_line" | awk -F'|' '{gsub(/^[ 	]+|[ 	]+$/,"",$2); gsub(/\([0-9]+\)[[:space:]]*/,"",$2); print $2}')
            _psu_reading=$(echo "$_psu_line" | awk -F'|' '{gsub(/^[ 	]+|[ 	]+$/,"",$4); print $4}')
            [ -z "$_psu_name" ] && continue
            _PSU_DETECTED=$(( _PSU_DETECTED + 1 ))
            if echo "$_psu_stat" | grep -qi "^OK"; then
                _PSU_ENTRIES+=("${_psu_name}|${_psu_reading:-Presence detected}|OK")
            else
                _PSU_ENTRIES+=("${_psu_name}|${_psu_reading:-${_psu_stat}}|FAIL")
                _PSU_FAIL_COUNT=$(( _PSU_FAIL_COUNT + 1 ))
            fi
        done <<< "$_SDR_PSU"
    fi

    # Fall back to ipmicfg -summary if SDR had no PSU rows
    if [ "$_PSU_DETECTED" -eq 0 ]; then
        while IFS= read -r _psu_line; do
            [ -z "$_psu_line" ] && continue
            _psu_num=$(echo "$_psu_line" | grep -oE '(Power Supply|PSU|PS)[[:space:]]*[0-9]+' | grep -oE '[0-9]+' | head -1)
            _psu_status=$(echo "$_psu_line" | cut -d: -f2 | xargs)
            [ -z "$_psu_num" ] && continue
            _PSU_DETECTED=$(( _PSU_DETECTED + 1 ))
            if echo "$_psu_status" | grep -qi "Power OK\|Present.*OK"; then
                _PSU_ENTRIES+=("PSU${_psu_num}|${_psu_status}|OK")
            else
                _PSU_ENTRIES+=("PSU${_psu_num}|${_psu_status}|FAIL")
                _PSU_FAIL_COUNT=$(( _PSU_FAIL_COUNT + 1 ))
            fi
        done < <(ipmicfg -summary 2>/dev/null             | grep -iE "Power Supply|PSU|^PS[[:space:]]+[0-9]")
    fi
fi
unset _SDR_FULL_PSU _SDR_PSU


# =============================================================================
#  GATHER: NVMe health via nvme smart-log
#  smartctl misses NVMe-specific fields; nvme smart-log gives % used,
#  available spare, and critical warning bits per controller.
# =============================================================================
declare -a _NVME_DEVS _NVME_MODELS _NVME_PCT _NVME_SPARE _NVME_WARN _NVME_STATUS
_NVME_FAIL=0
if [ "${SKIP_NVME_HEALTH:-0}" != "1" ] && command -v nvme >/dev/null 2>&1; then
    for _nc in /dev/nvme[0-9]*; do
        [[ "$(basename "$_nc")" =~ ^nvme[0-9]+$ ]] || continue
        [ -e "$_nc" ] || continue
        _nm=$(nvme id-ctrl "$_nc" 2>/dev/null \
            | awk -F: '/^mn /{gsub(/^[ \t]+/,"",$2); print $2; exit}' | xargs)
        [ -z "$_nm" ] && _nm="(unknown)"
        _ns=$(nvme smart-log "$_nc" 2>/dev/null)
        _np=$(printf '%s' "$_ns" | awk -F: '/percentage_used/{gsub(/[^0-9]/,"",$2);print $2+0}')
        _nsp=$(printf '%s' "$_ns" | awk -F: '/available_spare[^_]/{gsub(/[^0-9]/,"",$2);print $2+0}')
        _nw=$(printf '%s' "$_ns" | awk -F: '/critical_warning/{gsub(/[^0-9a-fx]/,"",$2);print $2}')
        [ -z "$_np" ] && _np="-"
        [ -z "$_nsp" ] && _nsp="-"
        [ -z "$_nw" ] && _nw="-"
        _nst="PASS"
        [ "$_np" != "-" ] && [ "$_np" -ge "$NVME_PCT_USED_FAIL" ] 2>/dev/null && _nst="FAIL"
        [ "$_nsp" != "-" ] && [ "$_nsp" -lt "$NVME_SPARE_WARN" ] 2>/dev/null && [ "$_nst" = "PASS" ] && _nst="WARN"
        [ "$_nw" != "-" ] && [ "$_nw" != "0x00" ] && [ "$_nw" != "0" ] && _nst="FAIL"
        _NVME_DEVS+=("$_nc"); _NVME_MODELS+=("$_nm")
        _NVME_PCT+=("$_np"); _NVME_SPARE+=("$_nsp")
        _NVME_WARN+=("$_nw"); _NVME_STATUS+=("$_nst")
        [ "$_nst" = "FAIL" ] && _NVME_FAIL=$(( _NVME_FAIL + 1 ))
    done
fi


# =============================================================================
#  GATHER: Bond interface health from /proc/net/bonding/
# =============================================================================
declare -a _BOND_ENTRIES=()
if [ "${SKIP_BOND_CHECK:-0}" != "1" ]; then
    for _bp in /proc/net/bonding/bond*; do
        [ -r "$_bp" ] || continue
        _bn=$(basename "$_bp")
        _bmode=$(awk -F: '/^Bonding Mode:/{gsub(/^[ \t]+/,"",$2);print $2}' "$_bp" | xargs)
        _btotal=$(grep -c "^Slave Interface:" "$_bp" 2>/dev/null || echo 0)
        _bactive=$(grep -c "MII Status: up" "$_bp" 2>/dev/null || echo 0)
        _bdown=$(awk '/^Slave Interface:/{iface=$NF}/MII Status: down/{print iface}' "$_bp" | paste -sd ',' -)
        if [ "$_bactive" -eq 0 ]; then
            _bv="FAIL"
        elif [ -n "$_bdown" ]; then
            _bv="WARN"
        else
            _bv="PASS"
        fi
        _bd="${_bactive}/${_btotal} slaves up  mode: ${_bmode:-unknown}"
        [ -n "$_bdown" ] && _bd="${_bd}  down: ${_bdown}"
        _BOND_ENTRIES+=("${_bn}|${_bd}|${_bv}")
    done
fi


# =============================================================================
#  GATHER: lspci summary -- RAID, NICs, HBAs, NVMe (deduped, no VGA/ASPEED)
# =============================================================================
declare -A _PCI_SEEN=()
if [ "${SKIP_LSPCI:-0}" != "1" ]; then
    # Only show true add-in cards (have Physical Slot in lspci -v).
    # Onboard devices -- even on high bus numbers on EPYC -- have no Physical Slot.
    # Only include RAID controllers and 10G+ NICs; skip NVMe and onboard 1G.
    _SLOTTED_PCI=$(lspci -v 2>/dev/null | awk '
        /^[0-9a-f]/{bdf=$1; has_slot=0}
        /Physical Slot:/{has_slot=1}
        /^$/ && has_slot{print bdf}
    ')
    if [ -n "$_SLOTTED_PCI" ]; then
        while IFS= read -r _bdf; do
            _pl=$(printf '%s
' "$_LSPCI" | grep -i "^${_bdf} ")
            [ -z "$_pl" ] && continue
            # Include RAID controllers
            if echo "$_pl" | grep -qiE "RAID|MegaRAID|Fibre Channel"; then
                _ps=$(echo "$_pl" | sed -E 's/^[0-9a-f:.]+ //; s/^[^:]+:[[:space:]]*//)
                _PCI_SEEN["$_ps"]=$(( ${_PCI_SEEN["$_ps"]:-0} + 1 ))
            # Include 10G+ NICs only
            elif echo "$_pl" | grep -qiE "Ethernet" && echo "$_pl" | grep -qiE                 "10-Gigabit|10GbE|10GBASE|X520|X540|X550|X710|X722|XL710|XXV710|E810|82599|Connect[Xx]|57711|57810|57840|BCM578|NetXtreme-E|Aquantia|Chelsio"; then
                _ps=$(echo "$_pl" | sed -E 's/^[0-9a-f:.]+ //; s/^[^:]+:[[:space:]]*//)
                _PCI_SEEN["$_ps"]=$(( ${_PCI_SEEN["$_ps"]:-0} + 1 ))
            fi
        done <<< "$_SLOTTED_PCI"
    fi
    unset _SLOTTED_PCI _bdf _pl
fi

# =============================================================================
#  GATHER: SEL events, split by severity
# =============================================================================
_SEL_CRITICAL=""; _SEL_WARN=""; _SEL_INFO=""
_SEL_CRIT_COUNT=0; _SEL_WARN_COUNT=0; _SEL_INFO_COUNT=0
if [ "${SKIP_SEL:-0}" != "1" ]; then
    _SEL_RAW=$(ipmicfg -sel list 2>/dev/null \
        | grep -vE "^$|^SEL|No.*entries|List is empty|ACPowerOn|AC Power on|First AC" \
        | grep -vE "^[[:space:]]*-+[[:space:]]*$" \
        | grep -v "^[[:space:]]*$")
    if [ -n "$_SEL_RAW" ]; then
        while IFS= read -r _sl; do
            [ -z "$_sl" ] && continue
            if echo "$_sl" | grep -qi "Severity:Critical"; then
                _SEL_CRITICAL="${_SEL_CRITICAL}${_sl}
"; _SEL_CRIT_COUNT=$(( _SEL_CRIT_COUNT + 1 ))
            elif echo "$_sl" | grep -qi "Severity:Warning"; then
                _SEL_WARN="${_SEL_WARN}${_sl}
"; _SEL_WARN_COUNT=$(( _SEL_WARN_COUNT + 1 ))
            else
                _SEL_INFO="${_SEL_INFO}${_sl}
"; _SEL_INFO_COUNT=$(( _SEL_INFO_COUNT + 1 ))
            fi
        done <<< "$_SEL_RAW"
    fi
fi


# =============================================================================
#  SERVER SUMMARY BOX
# =============================================================================
_BOARD_RAW=$(dmidecode -t 2 2>/dev/null | grep 'Product Name' | awk '{print $NF}' | tr -d '[:space:]')
_CURRENT_FW=$(ipmicfg -ver 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
_CURRENT_BIOS=$(dmidecode -s bios-version 2>/dev/null | tr -d '[:space:]')
_IPMI_UPDATE_MSG=" $(printf "%b UNABLE TO DETERMINE %b" "$DIM" "$RST")"
_BIOS_UPDATE_MSG=" $(printf "%b UNABLE TO DETERMINE %b" "$DIM" "$RST")"

_fw_normalize() { echo "$1" | awk -F. '{ printf "%02d.%02d.%02d",$1+0,$2+0,$3+0 }'; }

_LATEST_BIOS="${BIOS_LATEST[${_BOARD_RAW}]:-}"
_LATEST_FW="${IPMI_LATEST[${_BOARD_RAW}]:-}"

if [ -n "$_LATEST_FW" ] && [ -n "$_CURRENT_FW" ]; then
    _cn=$(_fw_normalize "$_CURRENT_FW"); _ln=$(_fw_normalize "$_LATEST_FW")
    if [[ "$_cn" < "$_ln" ]]; then
        _IPMI_UPDATE_MSG=" $(printf "%b%b UPDATE REQUIRED -> %s %b" "$BGR" "$BOLD" "$_LATEST_FW" "$RST")"
    elif [[ "$_cn" = "$_ln" ]]; then
        _IPMI_UPDATE_MSG=" $(printf "%b%b LATEST %b" "$BOLD" "$G" "$RST")"
    fi
elif [ -z "$_LATEST_FW" ] && [ -n "$_BOARD_RAW" ]; then
    _IPMI_UPDATE_MSG=" $(printf "%b (no version on record) %b" "$DIM" "$RST")"
fi

if [ -n "$_LATEST_BIOS" ] && [ -n "$_CURRENT_BIOS" ]; then
    _cb=$(_fw_normalize "$_CURRENT_BIOS"); _lb=$(_fw_normalize "$_LATEST_BIOS")
    if [[ "$_cb" < "$_lb" ]]; then
        _BIOS_UPDATE_MSG=" $(printf "%b%b UPDATE REQUIRED -> %s %b" "$BGR" "$BOLD" "$_LATEST_BIOS" "$RST")"
    elif [[ "$_cb" = "$_lb" ]]; then
        _BIOS_UPDATE_MSG=" $(printf "%b%b LATEST %b" "$BOLD" "$G" "$RST")"
    fi
fi

if [ "${SKIP_SERVER_SUMMARY:-0}" != "1" ]; then
box_open "SERVER SUMMARY" "$C"
bkv "Hostname:" "$(uname -n)" "$C" "$BOLD"
bdivider

# -- CPU ----------------------------------------------------------------------
CPU_COUNT=$(grep "physical id" /proc/cpuinfo | sort -u | wc -l)
CPU_NAME=$(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | xargs \
    | sed -E 's/\(R\)//g;s/\(TM\)//g;s/CPU //;s/ @ [0-9.]+GHz//;s/  +/ /g')
[ "$CPU_COUNT" -eq 1 ] && bkv "CPU:" "1x ${CPU_NAME}" "$G" "$Y"
[ "$CPU_COUNT" -ge 2 ] && bkv "CPU:" "${CPU_COUNT}x ${CPU_NAME}" "$G" "$Y"
bkv "Physical CPUs:" "$CPU_COUNT" "$G" "$C"
bkv "Logical Cores:" "$(grep 'model name' /proc/cpuinfo | wc -l)" "$G" "$C"
unset CPU_COUNT CPU_NAME

bdivider

# -- Board / firmware ---------------------------------------------------------
bkv "Motherboard:"  "$(dmidecode -t 2 | grep 'Product Name' | awk '{print $3}')" "$G" "$Y"
bkv "Manufacturer:" "$(dmidecode -t 2 | grep Manufacturer | cut -d: -f2 | xargs)" "$G" "$Y"
bkv "BIOS Version:" "${_CURRENT_BIOS}${_BIOS_UPDATE_MSG}" "$G" "$C"
bkv "IPMI Version:" "${_CURRENT_FW}${_IPMI_UPDATE_MSG}" "$G" "$C"

# -- Fan mode check and auto-correction ---------------------------------------
# Only PCIe add-in cards (bus >= 01) trigger Heavy IO.
# Onboard RAID or 10G (bus 00) = Standard/Optimal is correct.
_FAN_MODE_RAW=$(ipmicfg -fan 2>/dev/null | grep -i "Current Fan Speed Mode" \
    | sed 's/.*:[[:space:]]*//' | tr -d '[]' | xargs)
if   printf '%s' "$_FAN_MODE_RAW" | grep -qi "Heavy IO"; then _FAN_MODE="Heavy IO"
elif printf '%s' "$_FAN_MODE_RAW" | grep -qi "Optimal";  then _FAN_MODE="Optimal"
elif printf '%s' "$_FAN_MODE_RAW" | grep -qi "Standard"; then _FAN_MODE="Standard"
elif printf '%s' "$_FAN_MODE_RAW" | grep -qi "Full";     then _FAN_MODE="Full Speed"
else _FAN_MODE="$_FAN_MODE_RAW"; fi

# PCIe add-in RAID card (not onboard -- bus != 00)
_HAS_RAID=0
printf '%s' "$_LSPCI" | grep -iE "RAID bus controller|MegaRAID" \
    | grep -vE "^00:" | grep -q . && _HAS_RAID=1

# PCIe add-in 10GbE NIC (not onboard -- bus != 00)
_HAS_10G=0
printf '%s' "$_LSPCI" | grep -iE "Ethernet" | grep -vE "^00:" \
    | grep -qiE "10-Gigabit|10GbE|10GBASE|10G[ -]?SFP|X520|X540|X550|X710|X722|XL710|XXV710|E810|82599|Connect[Xx]-[3-7]|57711|57810|57840|BCM578|Aquantia|Chelsio T[3-6]|MT2[789]|MT4[0-9]" \
    && _HAS_10G=1

if [ "$_HAS_RAID" -eq 1 ] || [ "$_HAS_10G" -eq 1 ]; then
    TARGET_FAN_MODE_NUM=4; TARGET_FAN_MODE_NAME="Heavy IO"
    _FAN_REASON=""
    [ "$_HAS_RAID" -eq 1 ] && _FAN_REASON="PCIe RAID"
    [ "$_HAS_10G"  -eq 1 ] && _FAN_REASON="${_FAN_REASON:+$_FAN_REASON+}PCIe 10G"
else
    TARGET_FAN_MODE_NUM=0; TARGET_FAN_MODE_NAME="Standard"
    _FAN_REASON="no PCIe RAID/10G"
fi

_FAN_OK=0
case "$TARGET_FAN_MODE_NUM" in
    4) printf '%s' "$_FAN_MODE" | grep -qi "Heavy IO"          && _FAN_OK=1 ;;
    0) printf '%s' "$_FAN_MODE" | grep -qiE "Standard|Optimal" && _FAN_OK=1 ;;
esac

if [ "$_FAN_OK" -eq 1 ]; then
    bline "$(printf "  %b%-22s%b%b%b%s%b  %b(%s)%b" \
        "$G" "Fan Mode:" "$RST" "$BGG" "$BLK" "$_FAN_MODE" "$RST" "$DIM" "$_FAN_REASON" "$RST")"
else
    bline "$(printf "  %b%-22s%b%b%b%s -- FIXING to %s (%s)...%b" \
        "$G" "Fan Mode:" "$RST" "$BGR" "$BOLD" "${_FAN_MODE:-(unknown)}" "$TARGET_FAN_MODE_NAME" "$_FAN_REASON" "$RST")"
    ipmicfg -fan "$TARGET_FAN_MODE_NUM" &>/dev/null
    _FAN_MODE_NEW_RAW=$(ipmicfg -fan 2>/dev/null | grep -i "Current Fan Speed Mode" \
        | sed 's/.*:[[:space:]]*//' | tr -d '[]' | xargs)
    if   printf '%s' "$_FAN_MODE_NEW_RAW" | grep -qi "Heavy IO"; then _FAN_MODE_NEW="Heavy IO"
    elif printf '%s' "$_FAN_MODE_NEW_RAW" | grep -qi "Optimal";  then _FAN_MODE_NEW="Optimal"
    elif printf '%s' "$_FAN_MODE_NEW_RAW" | grep -qi "Standard"; then _FAN_MODE_NEW="Standard"
    else _FAN_MODE_NEW="$_FAN_MODE_NEW_RAW"; fi
    bline "$(printf "  %b%-22s%b%b%b%s%b" \
        "$G" "Fan Mode Now:" "$RST" "$BGG" "$BLK" "${_FAN_MODE_NEW:-(unknown)}" "$RST")"
fi
unset _HAS_RAID _HAS_10G TARGET_FAN_MODE_NUM TARGET_FAN_MODE_NAME _FAN_REASON _FAN_OK _FAN_MODE_NEW _FAN_MODE_NEW_RAW _FAN_MODE_RAW

bkv "Timezone:" "$(timedatectl 2>/dev/null | grep 'Time zone' | awk '{print $3,$4,$5}')" "$G" "$DIM"

bdivider

# -- PSU status ---------------------------------------------------------------
if [ "${SKIP_PSU_CHECK:-0}" != "1" ]; then
    if [ "$_PSU_DETECTED" -eq 0 ]; then
        bkv "PSU:" "no PSU data from ipmicfg" "$G" "$DIM"
    else
        for _pe in "${_PSU_ENTRIES[@]}"; do
            IFS='|' read -r _pl _ps _pv <<< "$_pe"
            case "$_pv" in
                OK)   bline "$(printf "  %b%-22s%b%b%b %s %b" "$G" "${_pl}:" "$RST" "$BGG" "$BLK" "$_ps" "$RST")" ;;
                WARN) bline "$(printf "  %b%-22s%b%b%b %s %b" "$G" "${_pl}:" "$RST" "$BGY" "$BLK" "$_ps" "$RST")" ;;
                FAIL) bline "$(printf "  %b%-22s%b%b%b %s %b" "$G" "${_pl}:" "$RST" "$BGR" "$BOLD" "$_ps" "$RST")" ;;
            esac
        done
        if [ "$_PSU_DETECTED" -lt "$PSU_EXPECTED_COUNT" ] 2>/dev/null; then
            bline "$(printf "  %b%-22s%b%b%b Only %d of %d PSUs detected %b" \
                "$G" "PSU Warning:" "$RST" "$BGR" "$BOLD" "$_PSU_DETECTED" "$PSU_EXPECTED_COUNT" "$RST")"
        fi
    fi
    unset _pe _pl _ps _pv
    bdivider
fi

# -- RAM ----------------------------------------------------------------------
dmidecode -t 17 | grep -iE "Part" \
    | grep -ve "NO DIMM" -ve "CPU" -ve "Not" -ve "PartNum" -ve "Empty" -ve "Series" \
    | sort -u > /tmp/_ram_check
RAM_TOTAL="$(free --giga -h -t | grep 'Mem:' | awk '{print $2}')"

if [ "$(<"/tmp/_ram_check" wc -l)" != "1" ]; then
    bline "$(printf "  %b%-22s%b%b%b %s -- WARNING: MISMATCH %b" "$G" "RAM:" "$RST" "$BGR" "$BOLD" "$RAM_TOTAL" "$RST")"
    bempty
    dmidecode -t 17 | grep -iE "Locator|Part" | grep -ve "Bank" \
        | sed -e 's/^[ \t]*//' | sed '0~2 a\\' \
        | while IFS= read -r line; do
            bline "$(printf "    %b%s%b" "$Y" "$line" "$RST")"
        done
else
    bline "$(printf "  %b%-22s%b%b%b%b %s -- MATCHES %b" "$G" "RAM:" "$RST" "$BGG" "$BLK" "$BOLD" "$RAM_TOTAL" "$RST")"
fi
rm -f /tmp/_ram_check

_DMI17=$(dmidecode -t 17 2>/dev/null)
_DIMM_LINES=$(printf '%s' "$_DMI17" | awk '
    function emit() { if(size!=""&&size!~/No Module/&&size!~/^[ \t]*$/) print size"|"type"|"speed"|"mfg"|"part; size="";type="";speed="";mfg="";part="" }
    BEGIN{size="";type="";speed="";mfg="";part=""}
    /^Memory Device$/                        {emit()}
    /^[ \t]*Size:/                           {sub(/^[ \t]*Size:[ \t]*/,"");size=$0}
    /^[ \t]*Type:/&&!/Type Detail/           {sub(/^[ \t]*Type:[ \t]*/,"");type=$0}
    /^[ \t]*Speed:/&&!/Configured/           {sub(/^[ \t]*Speed:[ \t]*/,"");speed=$0}
    /^[ \t]*Configured Memory Speed:/        {if(speed==""||speed~/Unknown/){sub(/^[ \t]*Configured Memory Speed:[ \t]*/,"");speed=$0}}
    /^[ \t]*Configured Clock Speed:/         {if(speed==""||speed~/Unknown/){sub(/^[ \t]*Configured Clock Speed:[ \t]*/,"");speed=$0}}
    /^[ \t]*Manufacturer:/                   {sub(/^[ \t]*Manufacturer:[ \t]*/,"");mfg=$0}
    /^[ \t]*Part Number:/                    {sub(/^[ \t]*Part Number:[ \t]*/,"");sub(/[ \t]+$/,"");part=$0}
    END{emit()}')
_RAM_ECC=""
dmidecode -t 16 2>/dev/null | grep -qiE "Error Correction Type:[[:space:]]*(Single|Multi|ECC)" && _RAM_ECC="ECC "
_DIMM_GROUPS=$(printf '%s\n' "$_DIMM_LINES" | grep -v '^$' | sort | uniq -c \
    | awk '{count=$1;$1="";sub(/^ /,"");print count"|"$0}')
_TOTAL_DIMMS=$(printf '%s\n' "$_DIMM_LINES" | grep -cv '^$')
if [ "$_TOTAL_DIMMS" -gt 0 ]; then
    while IFS='|' read -r count size type speed mfg part; do
        [ -z "$count" ] && continue
        size=$(echo "$size" | sed 's/ //g')
        speed=$(echo "$speed" | sed -E 's/ +/ /g;s/^ //;s/ $//')
        mfg=$(echo "$mfg" | sed -E 's/[ \t]+$//')
        part=$(echo "$part" | sed -E 's/[ \t]+$//')
        { [ -z "$mfg" ]  || [ "$mfg"  = "Unknown" ]; } && mfg=""
        { [ -z "$part" ] || [ "$part" = "Unknown" ]; } && part=""
        if [ -n "$mfg" ] && [ -n "$part" ]; then ident="${mfg}-${part}"
        elif [ -n "$part" ]; then ident="$part"
        elif [ -n "$mfg" ]; then  ident="$mfg"
        else                       ident="(unknown part)"; fi
        line="${count}x ${size} ${type} ${_RAM_ECC}${ident}"
        [ -n "$speed" ] && [ "$speed" != "Unknown" ] && line="${line} ${speed}"
        bline "$(printf "    %b%s%b" "$C" "$line" "$RST")"
    done <<< "$_DIMM_GROUPS"
fi
unset _DMI17 _DIMM_LINES _DIMM_GROUPS _TOTAL_DIMMS _RAM_ECC

bdivider

# -- Bond interface health ----------------------------------------------------
if [ "${SKIP_BOND_CHECK:-0}" != "1" ] && [ "${#_BOND_ENTRIES[@]}" -gt 0 ]; then
    bline "$(printf "  %b%bBond Interfaces:%b" "$BOLD" "$G" "$RST")"
    for _be in "${_BOND_ENTRIES[@]}"; do
        IFS='|' read -r _bn _bd _bv <<< "$_be"
        case "$_bv" in
            PASS) bline "$(printf "    %b%-12s%b %b%s%b" "$BGG$BLK" "$_bn" "$RST" "$G" "$_bd" "$RST")" ;;
            WARN) bline "$(printf "    %b%-12s%b %b%s%b" "$BGY$BLK" "$_bn" "$RST" "$Y" "$_bd" "$RST")" ;;
            FAIL) bline "$(printf "    %b%-12s%b %b%s%b" "$BGR$BOLD" "$_bn" "$RST" "$R" "$_bd" "$RST")" ;;
        esac
    done
    unset _be _bn _bd _bv
    bdivider
fi

# -- lspci summary ------------------------------------------------------------
if [ "${SKIP_LSPCI:-0}" != "1" ] && [ "${#_PCI_SEEN[@]}" -gt 0 ]; then
    bline "$(printf "  %b%bPCI Devices:%b" "$BOLD" "$G" "$RST")"
    for _ps in "${!_PCI_SEEN[@]}"; do
        _pc=${_PCI_SEEN["$_ps"]}
        if [ "$_pc" -gt 1 ]; then
            bline "$(printf "    %b%dx  %s%b" "$DIM" "$_pc" "$_ps" "$RST")"
        else
            bline "$(printf "    %b%s%b" "$DIM" "$_ps" "$RST")"
        fi
    done
    unset _ps _pc _pv _max
    bdivider
fi

# -- NVMe health table --------------------------------------------------------
if [ "${SKIP_NVME_HEALTH:-0}" != "1" ] && [ "${#_NVME_DEVS[@]}" -gt 0 ]; then
    bline "$(printf "  %b%bNVMe Health (nvme smart-log):%b" "$BOLD" "$G" "$RST")"
    bline "$(printf "    %b%-10s  %-28s  %-7s  %-7s  %-10s  %s%b" \
        "$BOLD" "Device" "Model" "Used%" "Spare%" "CritWarn" "Status" "$RST")"
    for _ni in "${!_NVME_DEVS[@]}"; do
        _ns="${_NVME_STATUS[$_ni]}"
        case "$_ns" in
            PASS) _nc="$G" ;;
            WARN) _nc="$Y" ;;
            *)    _nc="$R" ;;
        esac
        bline "$(printf "    %b%-10s%b  %-28s  %-7s  %-7s  %-10s  %b%s%b" \
            "$DIM" "$(basename "${_NVME_DEVS[$_ni]}")" "$RST" \
            "${_NVME_MODELS[$_ni]}" \
            "${_NVME_PCT[$_ni]}" \
            "${_NVME_SPARE[$_ni]}" \
            "${_NVME_WARN[$_ni]}" \
            "$_nc" "$_ns" "$RST")"
    done
    unset _ni _ns _nc
    bdivider
fi

# -- SEL event log ------------------------------------------------------------
if [ "${SKIP_SEL:-0}" != "1" ]; then
    _SEL_TOTAL=$(( _SEL_CRIT_COUNT + _SEL_WARN_COUNT + _SEL_INFO_COUNT ))
    if [ "$_SEL_TOTAL" -eq 0 ]; then
        bkv "SEL:" "no events" "$G" "$G"
    else
        _sel_summary="${_SEL_TOTAL} event(s)"
        [ "$_SEL_CRIT_COUNT" -gt 0 ] && _sel_summary="${_sel_summary}  ${_SEL_CRIT_COUNT} critical"
        [ "$_SEL_WARN_COUNT" -gt 0 ] && _sel_summary="${_sel_summary}  ${_SEL_WARN_COUNT} warning"
        [ "$_SEL_INFO_COUNT" -gt 0 ] && _sel_summary="${_sel_summary}  ${_SEL_INFO_COUNT} info"
        if [ "$_SEL_CRIT_COUNT" -gt 0 ]; then
            bkv "SEL:" "$_sel_summary" "$G" "$R"
        else
            bkv "SEL:" "$_sel_summary" "$G" "$Y"
        fi
        # Critical events in red
        if [ -n "$_SEL_CRITICAL" ]; then
            bline "$(printf "    %b%bCRITICAL:%b" "$BOLD" "$R" "$RST")"
            printf '%s\n' "$_SEL_CRITICAL" | while IFS= read -r _sl; do
                [ -z "$_sl" ] && continue
                _sv=$(printf '%s' "$_sl" | sed -E 's/\x1b\[[0-9;:]*[mGKHFJA-Za-z]//g')
                [ ${#_sv} -gt 68 ] && _sl="${_sv:0:65}..."
                bline "$(printf "      %b%s%b" "$R" "$_sl" "$RST")"
            done
        fi
        # Warning events in amber
        if [ -n "$_SEL_WARN" ]; then
            bline "$(printf "    %b%bWARNING:%b" "$BOLD" "$Y" "$RST")"
            printf '%s\n' "$_SEL_WARN" | while IFS= read -r _sl; do
                [ -z "$_sl" ] && continue
                _sv=$(printf '%s' "$_sl" | sed -E 's/\x1b\[[0-9;:]*[mGKHFJA-Za-z]//g')
                [ ${#_sv} -gt 68 ] && _sl="${_sv:0:65}..."
                bline "$(printf "      %b%s%b" "$Y" "$_sl" "$RST")"
            done
        fi
        # Info/OK events dimmed
        if [ -n "$_SEL_INFO" ]; then
            bline "$(printf "    %b%bINFO:%b" "$BOLD" "$DIM" "$RST")"
            printf '%s\n' "$_SEL_INFO" | while IFS= read -r _sl; do
                [ -z "$_sl" ] && continue
                _sv=$(printf '%s' "$_sl" | sed -E 's/\x1b\[[0-9;:]*[mGKHFJA-Za-z]//g')
                [ ${#_sv} -gt 68 ] && _sl="${_sv:0:65}..."
                bline "$(printf "      %b%s%b" "$DIM" "$_sl" "$RST")"
            done
        fi
    fi
    bdivider
fi

bkv "OS:" "$(grep PRETTY_NAME /etc/*release 2>/dev/null | cut -d'"' -f2)" "$G" "$M"
box_close "$C"
fi # END: Server summary


# =============================================================================
#  TOOL INSTALLATION RESULT BOX
# =============================================================================
_TOOL_BITS=""
for entry in "${_TOOL_STATUSES[@]}"; do
    name="${entry%%=*}"; state="${entry##*=}"
    token=$(tool_state_token "$state")
    [ -n "$_TOOL_BITS" ] && _TOOL_BITS="${_TOOL_BITS}, "
    _TOOL_BITS="${_TOOL_BITS}${BOLD}${name}${RST}: ${token}"
done
_TOOL_VIS=$(printf '%s' "  $_TOOL_BITS  " | sed -E 's/\x1b\[[0-9;:]*[mGKHFJA-Za-z]//g')
_TOOL_VLEN=${#_TOOL_VIS}
_TOOL_OLD_W=$W; _TOOL_OLD_INNER=$INNER
[ "$_TOOL_VLEN" -gt "$W" ] && { W=$_TOOL_VLEN; INNER=$_TOOL_VLEN; }

if [ "${SKIP_TOOL_BOX:-0}" != "1" ]; then
box_open "TOOL INSTALLATION" "$C"
bline "  $_TOOL_BITS"
box_close "$C"
fi

W=$_TOOL_OLD_W; INNER=$_TOOL_OLD_INNER
unset _TOOL_BITS _TOOL_VIS _TOOL_VLEN _TOOL_OLD_W _TOOL_OLD_INNER _TOOL_STATUSES


# =============================================================================
#  STORAGE BOX
# =============================================================================
RAID_CARD=$(storcli /c0 show 2>/dev/null | grep -c "Product Name")
RAID_PD_COUNT=$(storcli /c0 show 2>/dev/null | grep -i "Physical Drives" | head -1 \
    | awk -F'=' '{print $2}' | xargs)
[ -z "$RAID_PD_COUNT" ] && RAID_PD_COUNT=0
RAID_DRIVE_ROWS=$(storcli /call /eall /sall show 2>/dev/null \
    | awk '/[0-9]+:[0-9]+/ && /UGood|Onln|Offln|UBad|GHS|DHS|JBOD/' | wc -l)

if [ "$RAID_CARD" -gt 0 ] 2>/dev/null && \
   { [ "$RAID_PD_COUNT" -gt 0 ] 2>/dev/null || [ "$RAID_DRIVE_ROWS" -gt 0 ] 2>/dev/null; }; then
    IS_RAID=true
else
    IS_RAID=false
fi

if [ "${SKIP_STORAGE:-0}" != "1" ]; then
box_open "STORAGE" "$M"

if $IS_RAID; then
    IS_BBU=1; IS_CV=1
    storcli /c0/bbu show &>/dev/null && IS_BBU=0
    storcli /c0/cv  show &>/dev/null && IS_CV=0
    CTRL_NAME=$(storcli /c0 show 2>/dev/null | grep 'Product Name' | cut -d'=' -f2 | xargs)
    CTRL_FW=$(storcli /c0 show 2>/dev/null | grep 'FW Package Build' | cut -d'=' -f2 | xargs)

    # RAID FW comparison
    _RAID_UPDATE_MSG=" $(printf "%b UNABLE TO DETERMINE IF LATEST FW %b" "$DIM" "$RST")"
    _RAID_FW_LIST=$(wget -q -O- "$RAID_FW_URL" 2>/dev/null)
    if [ -n "$_RAID_FW_LIST" ]; then
        _RAID_MODEL=""
        for _tok in $CTRL_NAME; do
            echo "$_RAID_FW_LIST" | grep -qi "^${_tok}=" && _RAID_MODEL="$_tok" && break
        done
        [ -z "$_RAID_MODEL" ] && _RAID_MODEL=$(echo "$CTRL_NAME" | grep -oE '[0-9]{4}' | head -1)
        if [ -n "$_RAID_MODEL" ]; then
            _LATEST_RAID_FW=$(echo "$_RAID_FW_LIST" | grep -i "^${_RAID_MODEL}=" | cut -d'=' -f2 | tr -d '[:space:]')
            if [ "$_LATEST_RAID_FW" = "EOL" ]; then
                _RAID_UPDATE_MSG=" $(printf "%b%b !! END OF LIFE -- NO UPDATES %b" "$BGR" "$BOLD" "$RST")"
            elif [ -n "$_LATEST_RAID_FW" ]; then
                _crn=$(echo "$CTRL_FW"         | tr '-' '.' | awk -F. '{printf "%05d%05d%05d%05d",$1+0,$2+0,$3+0,$4+0}')
                _lrn=$(echo "$_LATEST_RAID_FW" | tr '-' '.' | awk -F. '{printf "%05d%05d%05d%05d",$1+0,$2+0,$3+0,$4+0}')
                if [[ "$_crn" < "$_lrn" ]]; then
                    _RAID_UPDATE_MSG=" $(printf "%b%b UPDATE REQUIRED -> %s %b" "$BGR" "$BOLD" "$_LATEST_RAID_FW" "$RST")"
                elif [[ "$_crn" = "$_lrn" ]]; then
                    _RAID_UPDATE_MSG=" $(printf "%b%b LATEST %b" "$BOLD" "$G" "$RST")"
                fi
            fi
        fi
    fi

    bkv "RAID Controller:" "$CTRL_NAME" "$G" "$Y"
    bkv "Card Firmware:"   "${CTRL_FW}${_RAID_UPDATE_MSG}" "$G" "$C"

    if [ "$IS_BBU" -eq 0 ] || [ "$IS_CV" -eq 0 ]; then
        bline "$(printf "  %b%-22s%b%b%b Yes %b" "$G" "BBU/CV:" "$RST" "$BGG" "$BLK" "$RST")"
    else
        bline "$(printf "  %b%-22s%b%b%s%b" "$G" "BBU/CV:" "$RST" "$DIM" "none detected" "$RST")"
    fi

    # Virtual Drives
    _VD_OUT=$(storcli /call /vall show 2>/dev/null)
    _VD_HDR=$(printf '%s' "$_VD_OUT" | grep -E "^DG/VD" | head -1)
    _VD_ROWS=$(printf '%s' "$_VD_OUT" | grep -E "^[0-9]+/[0-9]+")
    if [ -n "$_VD_ROWS" ]; then
        _VD_DIV=$(printf '%s' "$_VD_HDR" | sed 's/./-/g')
        bdivider
        bline "$(printf "  %b%bVirtual Drives:%b" "$BOLD" "$G" "$RST")"
        bempty
        bline "$(printf "    %b%s%b" "$DIM" "$_VD_DIV" "$RST")"
        bline "$(printf "    %b%s%b" "$BOLD" "$_VD_HDR" "$RST")"
        bline "$(printf "    %b%s%b" "$DIM" "$_VD_DIV" "$RST")"
        while IFS= read -r _vd_line; do
            bline "$(printf "    %b%s%b" "$C" "$_vd_line" "$RST")"
        done < <(printf '%s\n' "$_VD_ROWS")
        bline "$(printf "    %b%s%b" "$DIM" "$_VD_DIV" "$RST")"
        bempty
    fi
    unset _VD_OUT _VD_HDR _VD_ROWS _VD_DIV _vd_line

    # Physical Drives table
    _PD_OUT=$(storcli /call /eall /sall show 2>/dev/null)
    _PD_ROWS=$(printf '%s' "$_PD_OUT" | grep -E "^[0-9]+:[0-9]+" | grep -E "UGood|Onln|Offln|UBad|GHS|DHS|JBOD")
    if [ -n "$_PD_ROWS" ]; then
        bdivider
        bline "$(printf "  %b%bPhysical Drives:%b" "$BOLD" "$G" "$RST")"
        bempty
        _PD_HDR=$(printf "%-9s %-5s %-2s %-9s %-4s %-3s %s" "Slot" "State" "DG" "Size" "Intf" "Med" "Model")
        bline "$(printf "    %b%s%b" "$DIM" "$_PD_HDR" "$RST")"
        while IFS= read -r _pd_line; do
            _pd_fmt=$(printf '%s' "$_pd_line" | awk '{size=$5" "$6;model=$12" "$13;printf "%-9s %-5s %-2s %-9s %-4s %-3s %s",$1,$3,$4,size,$7,$8,model}')
            bline "$(printf "    %b%s%b" "$C" "$_pd_fmt" "$RST")"
        done < <(printf '%s\n' "$_PD_ROWS")
        bempty
    fi
    unset _PD_OUT _PD_ROWS _pd_line _pd_fmt _PD_HDR

    bdivider
    bline "$(printf "  %b%bHard Drives:%b" "$BOLD" "$G" "$RST")"
    bempty

    # Per-drive SMART (RAID)
    while read -r eid_slt did state; do
        smart_out=$(smartctl -a -d "megaraid,${did}" /dev/bus/0 2>/dev/null)
        model=$(printf '%s' "$smart_out"  | grep -E "Device Model|Model Number" | head -1 | cut -d: -f2 | xargs)
        serial=$(printf '%s' "$smart_out" | grep "Serial Number"                | head -1 | cut -d: -f2 | xargs)
        size=$(printf '%s' "$smart_out"   | grep "User Capacity"                | head -1 | cut -d'[' -f2 | cut -d']' -f1 | xargs)
        fw=$(printf '%s' "$smart_out"     | grep "Firmware Version"             | head -1 | cut -d: -f2 | xargs)
        case "$state" in
            UGood) state_label="Unconfigured Good"   ;;
            Onln)  state_label="Online"              ;;
            Offln) state_label="Offline"             ;;
            UBad)  state_label="Unconfigured Bad"    ;;
            GHS)   state_label="Global Hot Spare"    ;;
            DHS)   state_label="Dedicated Hot Spare" ;;
            JBOD)  state_label="JBOD"                ;;
            *)     state_label="$state"              ;;
        esac
        bline "$(printf "  %b%bSlot %s%b  %b[%s]%b" "$BOLD" "$C" "${eid_slt}" "$RST" "$DIM" "$state_label" "$RST")"
        disk_type="HDD"
        if printf '%s' "$smart_out" | grep -qi "NVM Express\|nvme"; then disk_type="NVMe"
        elif printf '%s' "$smart_out" | grep -qi "Solid State\|Rotation Rate.*Solid"; then disk_type="SSD"
        elif ! printf '%s' "$smart_out" | grep -q "Rotation Rate"; then disk_type="SSD"; fi
        sst_badge=$(sst_badge_for "$serial")
        bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Type:"     "$RST" "$Y"   "$disk_type"           "$RST")"
        bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Model:"    "$RST" "$Y"   "${model:-(unknown)}"  "$RST")"
        bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Serial:"   "$RST" "$DIM" "${serial:-(unknown)}" "$RST")"
        bline "$(printf "    %b%-20s%b%b%s%b" "$G" "Size:"     "$RST" "$C"   "${size:-(unknown)}"   "$RST")"
        bline "$(printf "    %b%-20s%b%b%s%b%s" "$G" "Firmware:" "$RST" "$C" "${fw:-(unknown)}" "$RST" "${sst_badge:+  $sst_badge}")"
        is_ssd=$(printf '%s' "$smart_out" | grep -i "Solid State\|SSD\|Rotation Rate.*Solid" | wc -l)
        [ "$is_ssd" -eq 0 ] && rot=$(printf '%s' "$smart_out" | grep "Rotation Rate" | grep -v "Solid" | wc -l) && [ "$rot" -eq 0 ] && is_ssd=1
        print_smart_attrs "$smart_out" "$is_ssd"
        bempty
    done < <(storcli /call /eall /sall show 2>/dev/null \
        | awk '/[0-9]+:[0-9]+/ && /UGood|Onln|Offln|UBad|GHS|DHS|JBOD/ { print $1,$2,$3 }')

else
    # Non-RAID
    if [ "$RAID_CARD" -gt 0 ] 2>/dev/null; then
        CTRL_NAME=$(storcli /c0 show 2>/dev/null | grep 'Product Name' | cut -d'=' -f2 | xargs)
        bkv "Controller:" "${CTRL_NAME} (HBA / pass-through)" "$G" "$Y"
        bdivider
    fi
    bline "$(printf "  %b%bHard Drives:%b" "$BOLD" "$G" "$RST")"
    bempty
    while IFS= read -r dev; do
        [ -b "$dev" ] || continue
        drive_entry "$dev" -a "$dev"
    done < <(lsblk -dno NAME,TYPE 2>/dev/null | awk '$2=="disk"{print "/dev/"$1}' | sort)
fi

# Block device map
bdivider
bline "$(printf "  %b%bBlock Devices: (lsblk)%b" "$BOLD" "$G" "$RST")"
bempty

# Build model map from lsblk, fill NVMe gaps with nvme id-ctrl
declare -A _lb_model_map=()
while IFS= read -r _lm; do
    _lmn=$(echo "$_lm" | awk '{print $1}')
    _lmv=$(echo "$_lm" | cut -d' ' -f2- | xargs)
    [ -n "$_lmn" ] && _lb_model_map["$_lmn"]="$_lmv"
done < <(lsblk -dno NAME,MODEL 2>/dev/null)
if command -v nvme >/dev/null 2>&1; then
    for _nctrl in /dev/nvme[0-9]*; do
        [[ "$(basename "$_nctrl")" =~ ^nvme[0-9]+$ ]] || continue
        _cidx=$(basename "$_nctrl" | grep -oE '[0-9]+$')
        _nsname="nvme${_cidx}n1"
        if [ -z "${_lb_model_map[$_nsname]:-}" ]; then
            _nmod=$(nvme id-ctrl "$_nctrl" 2>/dev/null | awk -F: '/^mn /{gsub(/^[ \t]+/,"",$2); print $2; exit}' | xargs)
            [ -n "$_nmod" ] && _lb_model_map["$_nsname"]="$_nmod"
        fi
    done
fi

lsblk -e 7 -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT --noheadings 2>/dev/null | while IFS= read -r _lb_line; do
    [ -z "$_lb_line" ] && continue
    _lb_dev=$(printf '%s' "$_lb_line" | awk '{print $1}' | tr -d 'â??â??â??â?? ')
    # Use pre-built model map (includes nvme id-ctrl for NVMe) -- no smartctl call per line
    _lb_model="${_lb_model_map[$_lb_dev]:-}"
    if printf '%s' "$_lb_line" | grep -qE "^[a-zA-Z]"; then
        bline "$(printf "    %b%-28s%b %b%s%b" "$C" "$_lb_line" "$RST" "$DIM" "$_lb_model" "$RST")"
    else
        bline "$(printf "    %b%-28s%b %b%s%b" "$DIM" "$_lb_line" "$RST" "$DIM" "$_lb_model" "$RST")"
    fi
done
bempty
box_close "$M"
fi # END: Storage


# =============================================================================
#  PER-DISK SMART BOXES (non-RAID only)
# =============================================================================
if ! $IS_RAID && [ "${SKIP_SMART_PER_DISK:-0}" != "1" ]; then
for dev in sda sdb sdc sdd; do
    [ -b "/dev/${dev}" ] || continue
    box_open "/dev/${dev} SMART" "$B"
    MODEL=$(smartctl -a "/dev/${dev}" 2>/dev/null | grep "Device Model"     | cut -d: -f2 | xargs)
    FW=$(   smartctl -a "/dev/${dev}" 2>/dev/null | grep "Firmware Version" | cut -d: -f2 | xargs)
    bkv "Device Model:" "$MODEL" "$G" "$Y"
    bkv "Firmware:"     "$FW"    "$G" "$C"
    bempty
    bline "$(printf "  %b%b%-4s %-30s   %s%b" "$BOLD" "$C" "ID#" "ATTRIBUTE" "VALUE" "$RST")"
    bline "$(printf "  %b%s%b" "$DIM" "$(rep "$(_HD)" 70)" "$RST")"
    smartctl -a "/dev/${dev}" 2>/dev/null \
        | grep -E "Power_On_Hours|Reallocated_Sector|Current_Pending|Wear_Leveling|Media_Wearout|Offline_Unco|Reported_Uncorrect|UDMA_CRC_Error|Total_LBAs_Written" \
        | while read -r id attr f v w t tp up wf raw; do
            case "$attr" in
                Media_Wearout_Indicator|Wear_Leveling_Count)
                    show="$v"; wcolor="$DIM"
                    [ "$v" -lt 80 ] 2>/dev/null && wcolor="$Y"
                    [ "$v" -lt 50 ] 2>/dev/null && wcolor="$R"
                    bline "$(printf "  %b%-4s %-30s   %s%b" "$wcolor" "$id" "$attr" "$show" "$RST")" ;;
                *)
                    show="$raw"
                    if { [ "$v" -lt "$t" ] 2>/dev/null; } || \
                       { [ "$raw" -gt 0 ] 2>/dev/null && echo "$attr" | grep -qE "Reallocated|Pending|Offline_Unco|Reported_Uncorrect|UDMA_CRC_Error"; }; then
                        bline "$(printf "  %b%-4s %-30s   %s%b" "$R"   "$id" "$attr" "$show" "$RST")"
                    else
                        bline "$(printf "  %b%-4s %-30s   %s%b" "$DIM" "$id" "$attr" "$show" "$RST")"
                    fi ;;
            esac
        done
    box_close "$B"
done
fi # END: Per-disk SMART

exit 0