#!/bin/bash
#
# mac-check.sh — Laptop Mate LLC intake diagnostic
# READ ONLY. Changes nothing on the machine.
#
# Run:  bash mac-check.sh
#
# Works on Intel and Apple Silicon. No install, no dependencies.
# Every command used is a stock macOS system binary.
# Appends one row per run to mac-check-log.csv beside this script.
#
# Prints a TECH TAG first (matches the paper intake tag — fill the
# blanks by hand), then the full diagnostic report below it.
#

RED=$'\033[0;31m'; GRN=$'\033[0;32m'; YEL=$'\033[0;33m'; BLD=$'\033[1m'; OFF=$'\033[0m'

SP_HW=$(/usr/sbin/system_profiler SPHardwareDataType 2>/dev/null)
ARCH=$(/usr/bin/uname -m)

line()  { printf '%s\n' "------------------------------------------------------------"; }
field() { printf '  %-22s %s\n' "$1" "$2"; }
explain() { printf '%-25s%s\n' "" "→ $1"; }

# ══════════════════════════════════════════════════════════════
# DATA COLLECTION — all values gathered here first so the tag can
# print immediately. Every command below is unchanged from prior
# verified runs; only the ORDER moved.
# ══════════════════════════════════════════════════════════════

# --- Identity ---
MODEL=$(printf '%s' "$SP_HW" | awk -F': ' '/Model Name/{print $2}')
MODEL_ID=$(printf '%s' "$SP_HW" | awk -F': ' '/Model Identifier/{print $2}')
SERIAL=$(printf '%s' "$SP_HW" | awk -F': ' '/Serial Number/{print $2}')
RAM=$(printf '%s' "$SP_HW" | awk -F': ' '/^ *Memory:/{print $2}')
OSVER=$(/usr/bin/sw_vers -productVersion)
OSBUILD=$(/usr/bin/sw_vers -buildVersion)

# Original setup/install date. Verified command (confirmed in a
# production IT-management vendor script): the timestamp on
# .AppleSetupDone marks when initial setup completed, which is
# effectively the OS's first run on this drive.
INSTALL_DATE=$(/usr/bin/stat -f "%SB" -t "%Y-%m-%d" /var/db/.AppleSetupDone 2>/dev/null)

if [ "$ARCH" = "arm64" ]; then
  CHIP=$(printf '%s' "$SP_HW" | awk -F': ' '/Chip/{print $2}')
  SPECS_LINE="$CHIP"
else
  CHIP=$(printf '%s' "$SP_HW" | awk -F': ' '/Processor Name/{print $2}')
  # Exact CPU SKU (e.g. "i5-1038NG7"), not just the generic name.
  # Verified: sysctl -n machdep.cpu.brand_string gives
  # "Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz" format on Intel Macs.
  CPU_BRAND=$(/usr/sbin/sysctl -n machdep.cpu.brand_string 2>/dev/null)
  SPECS_LINE="${CPU_BRAND:-$CHIP}"
fi

# macOS version number -> marketing name. Verified against Microsoft^H^H
# Apple release docs current as of Aug 2026. Needs a new case added
# each September when Apple ships a new major version.
OS_MAJOR="${OSVER%%.*}"
case "$OS_MAJOR" in
  27) OS_NAME="Golden Gate" ;;
  26) OS_NAME="Tahoe" ;;
  15) OS_NAME="Sequoia" ;;
  14) OS_NAME="Sonoma" ;;
  13) OS_NAME="Ventura" ;;
  12) OS_NAME="Monterey" ;;
  11) OS_NAME="Big Sur" ;;
  10) OS_NAME="Catalina or earlier" ;;
  *)  OS_NAME="unknown" ;;
esac

# Model Identifier -> marketing name. Small, honestly-sourced table —
# each entry verified against Apple's own support pages or AppleDB
# release records, not guessed. Falls back to blank (raw Model
# Identifier still shows separately) rather than ever printing an
# unverified name. Covers common resale-relevant models; expand only
# with confirmed sources, same discipline as the KNOWN DEFECTS table.
case "$MODEL_ID" in
  MacBookAir10,1)                    MODEL_NAME="MacBook Air (M1, 2020)" ;;
  MacBookAir9,1)                     MODEL_NAME="MacBook Air (2020, Intel)" ;;
  MacBookAir8,2)                     MODEL_NAME="MacBook Air (2019)" ;;
  MacBookAir8,1)                     MODEL_NAME="MacBook Air (2018)" ;;
  MacBookPro18,1|MacBookPro18,2)     MODEL_NAME="MacBook Pro (16-inch, 2021)" ;;
  MacBookPro18,3|MacBookPro18,4)     MODEL_NAME="MacBook Pro (14-inch, 2021)" ;;
  MacBookPro17,1)                    MODEL_NAME="MacBook Pro (13-inch, M1, 2020)" ;;
  MacBookPro16,3)                    MODEL_NAME="MacBook Pro (13-inch, 2020, Two TB3 ports)" ;;
  MacBookPro16,1|MacBookPro16,4)     MODEL_NAME="MacBook Pro (16-inch, 2019)" ;;
  MacBookPro15,1|MacBookPro15,3)     MODEL_NAME="MacBook Pro (15-inch, 2019)" ;;
  MacBookPro15,2|MacBookPro15,4)     MODEL_NAME="MacBook Pro (13-inch, 2019)" ;;
  *)                                  MODEL_NAME="" ;;
esac

# --- Battery ---
# Field names are undocumented IOKit output, shifted once already
# between Intel and Apple Silicon. Two traps:
#   1. MaxCapacity reads hardcoded 100 on Apple Silicon — useless.
#      Real health is AppleRawMaxCapacity / DesignCapacity.
#   2. DesignCapacity appears twice (top-level and nested inside
#      BatteryData). Matching on ' = ' (spaced) picks the right one.
BATT=$(/usr/sbin/ioreg -r -c AppleSmartBattery 2>/dev/null)
HEALTH=""
CYCLES=""
BATT_MAH=""
BATT_DESIGN=""
if [ -n "$BATT" ]; then
  HEALTH=$(printf '%s' "$BATT" | awk -F' = ' '
    /"DesignCapacity" = /      { if (d == "") d = $2 }
    /"AppleRawMaxCapacity" = / { if (m == "") m = $2 }
    END { if (d + 0 > 0 && m + 0 > 0) printf "%.1f", (m / d) * 100 }')
  CYCLES=$(printf '%s' "$BATT" | awk -F' = ' '/"CycleCount" = / { if (c == "") c = $2 } END { print c }')
  BATT_MAH=$(printf '%s' "$BATT" | awk -F' = ' '/"AppleRawMaxCapacity" = / { if (m == "") m = $2 } END { print m }')
  BATT_DESIGN=$(printf '%s' "$BATT" | awk -F' = ' '/"DesignCapacity" = / { if (d == "") d = $2 } END { print d }')
fi

# Apple's own official assessment, separate from the percentage we
# calculate above. Only two possible values since Catalina: "Normal"
# or "Service recommended". Cross-check — if this disagrees with our
# calculated percentage, that's worth a human look.
BATT_COND=$(/usr/sbin/system_profiler SPPowerDataType 2>/dev/null | awk -F': *' '/Condition:/{print $2; exit}')

# --- Storage ---
SMART=$(/usr/sbin/diskutil info disk0 2>/dev/null | awk -F': *' '/SMART Status/{print $2}')
# Must read the DATA volume, not "/" — on APFS "/" is the read-only
# signed system volume and reports capacity against system files only.
CAPACITY=$(/bin/df -h /System/Volumes/Data 2>/dev/null | awk 'NR==2 {print $2}')
FREE_PCT=$(/bin/df -h /System/Volumes/Data 2>/dev/null | awk 'NR==2 {gsub(/%/,"",$5); print 100-$5}')
FREE_SPACE=$(/bin/df -h /System/Volumes/Data 2>/dev/null | awk 'NR==2 {print $4}')

# macOS update check. Read-only listing (softwareupdate -l needs no
# sudo, installs nothing) but DOES need network — unlike everything
# else in this script. Verified: -l lists without installing; -i -a
# would install and requires sudo + possibly a restart, deliberately
# NOT included here.
UPDATES_AVAIL=$(/usr/sbin/softwareupdate -l 2>&1)
if printf '%s' "$UPDATES_AVAIL" | grep -qi "No new software available"; then
  UPDATE_STATE="current"
elif printf '%s' "$UPDATES_AVAIL" | grep -q "\*\|^ *-"; then
  UPDATE_STATE="available"
  UPDATE_COUNT=$(printf '%s' "$UPDATES_AVAIL" | grep -c "^\*\|^ *-")
else
  UPDATE_STATE="unknown"
fi

# --- Wipe check ---
USERS=$(/usr/bin/dscl . -list /Users UniqueID 2>/dev/null | awk '$2+0 >= 500 {print $1}')
USER_COUNT=$(printf '%s\n' "$USERS" | grep -c . || true)
[ "$USER_COUNT" -gt 0 ] 2>/dev/null && WIPE_STATE="not-wiped" || WIPE_STATE="clean"

FV=$(/usr/bin/fdesetup status 2>&1)
if printf '%s' "$FV" | grep -q "FileVault is On"; then
  FV_STATE="on"
elif printf '%s' "$FV" | grep -q "FileVault is Off"; then
  FV_STATE="off"
else
  FV_STATE="unclear"
fi

SIP=$(/usr/bin/csrutil status 2>/dev/null)
if printf '%s' "$SIP" | grep -q "enabled"; then
  SIP_STATE="enabled"
elif printf '%s' "$SIP" | grep -q "disabled"; then
  SIP_STATE="disabled"
else
  SIP_STATE="unreadable"
fi

if [ "$ARCH" = "arm64" ]; then
  FWPW_STATE="n/a"
else
  FWPW=$(/usr/sbin/firmwarepasswd -check 2>/dev/null)
  if printf '%s' "$FWPW" | grep -qi "Password Enabled: Yes"; then
    FWPW_STATE="set"
  elif printf '%s' "$FWPW" | grep -qi "Password Enabled: No"; then
    FWPW_STATE="not-set"
  else
    FWPW_STATE="unreadable"
  fi
fi

# iCloud sign-in, separate from Activation Lock. A Mac can have
# Activation Lock off but still carry the previous owner's Photos,
# Messages, and iCloud Drive if they only removed the lock without
# fully signing out. Presence check ONLY — the plist also contains
# the account email, which we deliberately do NOT read or log here.
ICLOUD_USER=$(/usr/bin/stat -f%Su /dev/console 2>/dev/null)
ICLOUD_STATE="none"
if [ -n "$ICLOUD_USER" ] && [ -f "/Users/$ICLOUD_USER/Library/Preferences/MobileMeAccounts.plist" ]; then
  ICLOUD_STATE="signed-in"
fi

# --- Fault history ---
PANIC_DIR="/Library/Logs/DiagnosticReports"
PANIC_FILES=$(/usr/bin/find "$PANIC_DIR" -maxdepth 1 ! -name ".*" \( -name "*.panic" -o -name "Kernel-*.ips" -o -name "panic-*.ips" \) 2>/dev/null)
if [ -n "$PANIC_FILES" ]; then
  PANICS=$(printf '%s\n' "$PANIC_FILES" | /usr/bin/wc -l | /usr/bin/tr -d ' ')
else
  PANICS=0
fi
LAST_PANIC=""
if [ "$PANICS" -gt 0 ] 2>/dev/null; then
  LAST=$(printf '%s\n' "$PANIC_FILES" | while read -r f; do
    /usr/bin/stat -f '%m %N' "$f" 2>/dev/null
  done | /usr/bin/sort -rn | /usr/bin/head -1 | /usr/bin/cut -d' ' -f2-)
  [ -n "$LAST" ] && LAST_PANIC="$(/bin/date -r "$(/usr/bin/stat -f '%m' "$LAST")" '+%Y-%m-%d' 2>/dev/null)  $(/usr/bin/basename "$LAST")"
fi

# --- Peripherals ---
SP_MISC=$(/usr/sbin/system_profiler SPDisplaysDataType SPCameraDataType SPAirPortDataType 2>/dev/null)
CAMERA_OK=0
printf '%s' "$SP_MISC" | grep -q "Camera\|FaceTime" && CAMERA_OK=1
WIFI=$(printf '%s' "$SP_MISC" | awk -F': ' '/Supported PHY Modes/{print $2; exit}')
GPU=$(printf '%s' "$SP_MISC" | awk -F': ' '/Chipset Model/{print $2}' | /usr/bin/paste -sd '; ' -)
GPU_CORES=""
if [ "$ARCH" = "arm64" ]; then
  GPU_CORES=$(printf '%s' "$SP_MISC" | awk -F': ' '/Total Number of Cores/{print $2; exit}')
fi
RES=$(printf '%s' "$SP_MISC" | awk -F': ' '/Resolution/{print $2; exit}')
BT_OK=0
/usr/sbin/system_profiler SPBluetoothDataType 2>/dev/null | grep -q "Bluetooth" && BT_OK=1

# Internal keyboard/trackpad share one combined device name in the
# IORegistry ("Apple Internal Keyboard / Trackpad") regardless of
# whether they're on the older USB bus or the newer SPI bus used
# since MacBook 8,1. Full ioreg -l tree searched (not limited to
# IOUSB) to catch it on either bus. Detects PRESENCE only — confirms
# macOS sees the controller, not that every key/zone works.
KBTP_OK=0
/usr/sbin/ioreg -l 2>/dev/null | grep -q "Apple Internal Keyboard" && KBTP_OK=1

# Thunderbolt/USB-C port count via controller enumeration.
PORT_COUNT=$(/usr/sbin/system_profiler SPThunderboltDataType 2>/dev/null | grep -c "Port:")

# --- Known defects ---
DEFECT=""
case "$MODEL_ID" in
  MacBookPro8,2|MacBookPro8,3)
    DEFECT="2011 15/17in — AMD dGPU failure. Test under GPU load before buying." ;;
  MacBookPro11,3)
    DEFECT="2013-14 15in — NVIDIA dGPU failure. Test under GPU load." ;;
  MacBook8,1|MacBook9,1|MacBook10,1)
    DEFECT="12in Retina — 1st/2nd gen butterfly keyboard. Test every key." ;;
  MacBookPro13,1|MacBookPro13,2|MacBookPro14,1|MacBookPro14,2)
    DEFECT="2016-17 13in — butterfly keyboard AND flexgate (display cable). Open lid fully, check backlight bar." ;;
  MacBookPro13,3|MacBookPro14,3|MacBookPro15,1|MacBookPro15,2|MacBookPro15,3|MacBookPro15,4)
    DEFECT="2016-19 — butterfly keyboard. Test every key." ;;
  MacBookAir8,1|MacBookAir8,2|MacBookAir9,1)
    DEFECT="2018-20 Intel Air — butterfly keyboard. Test every key." ;;
  MacBookPro10,1|MacBookPro11,1|MacBookPro11,2|MacBookPro12,1)
    DEFECT="2012-15 Retina — staingate (anti-reflective coating wear). Inspect screen at an angle." ;;
esac

# --- MDM / Activation Lock ---
AL=$(printf '%s' "$SP_HW" | awk -F': ' '/Activation Lock Status/{print $2}')
[ -z "$AL" ] && AL="n/a"
MDM=$(/usr/bin/profiles status -type enrollment 2>/dev/null)
if printf '%s' "$MDM" | grep -qi "Yes (User Approved)\|Enrolled via DEP: Yes"; then
  MDM_STATE="enrolled"
elif [ -z "$MDM" ]; then
  MDM_STATE="unread"
else
  MDM_STATE="clean"
fi

# --- Verdict ---
REASON=""
[ "$AL" = "Enabled" ] && REASON="Activation Lock enabled"
[ "$MDM_STATE" = "enrolled" ] && REASON="${REASON:+$REASON; }MDM enrolled"
[ -n "$HEALTH" ] && awk "BEGIN{exit !($HEALTH < 80)}" \
  && REASON="${REASON:+$REASON; }battery ${HEALTH}% (under 80)"
[ "${PANICS:-0}" -ge 3 ] 2>/dev/null \
  && REASON="${REASON:+$REASON; }${PANICS} kernel panics"

if [ "$WIPE_STATE" = "not-wiped" ] || [ "$ICLOUD_STATE" = "signed-in" ]; then
  VERDICT="WIPE FIRST"
  WIPE_REASONS=""
  [ "$WIPE_STATE" = "not-wiped" ] && WIPE_REASONS="${USER_COUNT} local account(s) still present"
  [ "$ICLOUD_STATE" = "signed-in" ] && WIPE_REASONS="${WIPE_REASONS:+$WIPE_REASONS; }iCloud account signed in"
  REASON="$WIPE_REASONS"
elif [ -n "$REASON" ]; then
  VERDICT="PARTS"
elif [ -z "$HEALTH" ]; then
  VERDICT="CHECK"
else
  VERDICT="RESELL"
fi

# Full report saved as its own .txt file per unit, so a seller has
# something to screenshot/attach and you have a complete per-machine
# archive beyond the CSV summary row. Colors stripped from the saved
# copy (a file full of raw \033[ escape codes is unreadable) — the
# ESC byte is substituted by bash before sed sees it, avoiding any
# dependence on sed's own \x escape support, which differs between
# BSD sed (macOS default) and GNU sed.
REPORT_DIR="$(cd "$(dirname "$0")" && pwd)/mac-check-reports"
/bin/mkdir -p "$REPORT_DIR" 2>/dev/null
REPORT_FILE="$REPORT_DIR/${SERIAL:-unknown}_$(date '+%Y-%m-%d_%H%M%S').txt"
exec > >(/usr/bin/tee "$REPORT_FILE")

# ══════════════════════════════════════════════════════════════
# TECH TAG — matches the paper intake tag. Fill blanks by hand.
# ══════════════════════════════════════════════════════════════
tagfield() { printf '  %-13s %s\n' "$1" "$2"; }

line
printf '%s\n' "${BLD}TECH TAG${OFF}  (fill blanks by hand)"
line
tagfield "Order #:" "__________        Date: $(date '+%Y-%m-%d')        Initial: ______"
line
if [ -n "$MODEL_NAME" ]; then
  tagfield "Model:" "$MODEL_NAME  ($MODEL_ID)"
else
  tagfield "Model:" "$MODEL / $MODEL_ID"
fi
line
SPECS_FULL="$SPECS_LINE"
[ -n "$RAM" ] && SPECS_FULL="$SPECS_FULL     RAM: $RAM"
tagfield "Specs:" "$SPECS_FULL"
line
tagfield "Motherboard:" "__________"
line
tagfield "LCD:" "__________     Resolution: ${RES:-not reported}"
line
if [ -n "$HEALTH" ]; then
  tagfield "Battery:" "__________ ; ${CYCLES:-?} CYCLES  (health ${HEALTH}%)"
else
  tagfield "Battery:" "__________ ; ${CYCLES:-?} CYCLES  (health unreadable)"
fi
line
tagfield "Serial #:" "$SERIAL          Color: __________"
line
tagfield "Storage:" "${CAPACITY:-?} / macOS $OS_NAME $OSVER"
line
if [ -n "$GPU_CORES" ]; then
  tagfield "Config:" "$CHIP, ${GPU_CORES}-core GPU   [order code: not available offline]"
else
  tagfield "Config:" "$CHIP   [order code: not available offline]"
fi
line
printf '\n'

# ══════════════════════════════════════════════════════════════
# FULL DIAGNOSTIC REPORT — safety-critical checks not on the tag.
# ══════════════════════════════════════════════════════════════

line
printf '%s\n' "${BLD}SELLABILITY${OFF}"
line
if [ "$AL" = "n/a" ]; then
  field "Activation Lock" "n/a — no T2 / Apple Silicon"
elif [ "$AL" = "Enabled" ]; then
  field "Activation Lock" "${RED}ENABLED — DO NOT BUY / DO NOT LIST${OFF}"
  explain "This alone can make a Mac unsellable. The original owner must remove it from their iCloud account before it can be erased or used."
else
  field "Activation Lock" "${GRN}$AL${OFF}"
fi
if /usr/sbin/nvram -p 2>/dev/null | grep -q fmm-mobileme-token-FMM; then
  field "Find My token" "present (FMM active)"
else
  field "Find My token" "absent"
fi
if [ "$MDM_STATE" = "enrolled" ]; then
  field "MDM enrolment" "${RED}ENROLLED — will re-lock after wipe${OFF}"
  explain "Even after erasing, this Mac will re-lock itself the moment it connects to Wi-Fi. Only the company that owns the management profile can release it."
elif [ "$MDM_STATE" = "unread" ]; then
  field "MDM enrolment" "could not read (try: sudo bash mac-check.sh)"
else
  field "MDM enrolment" "${GRN}not enrolled${OFF}"
fi

line
printf '%s\n' "${BLD}IDENTITY${OFF}"
line
field "Model"      "$MODEL"
field "Identifier" "$MODEL_ID"
field "Serial"     "$SERIAL"
field "RAM"        "$RAM"
field "macOS"      "$OS_NAME $OSVER ($OSBUILD)"
field "OS installed" "${INSTALL_DATE:-not reported}"
case "$UPDATE_STATE" in
  current)   field "Updates"  "${GRN}up to date${OFF}" ;;
  available) field "Updates"  "${YEL}${UPDATE_COUNT} available — not installed${OFF}" ;;
  *)         field "Updates"  "could not check (no internet, or Apple servers unreachable)" ;;
esac
if [ "$ARCH" = "arm64" ]; then
  field "Chip" "$CHIP (Apple Silicon)"
  field "OS ceiling" "current — supported going forward"
else
  field "CPU" "$SPECS_LINE (Intel)"
  field "OS ceiling" "${YEL}macOS 26 Tahoe is the last supported release${OFF}"
fi

line
printf '%s\n' "${BLD}KNOWN DEFECTS${OFF}"
line
if [ -n "$DEFECT" ]; then
  printf '  %s\n' "${YEL}${DEFECT}${OFF}"
else
  field "Known issues" "${GRN}none on record for this model${OFF}"
fi

line
printf '%s\n' "${BLD}BATTERY${OFF}"
line
if [ -z "$BATT" ]; then
  field "Battery" "none detected (desktop?)"
else
  field "Cycle count" "${CYCLES:-unreadable}"
  if [ -n "$HEALTH" ]; then
    field "Capacity" "$BATT_MAH / $BATT_DESIGN mAh"
    if awk "BEGIN{exit !($HEALTH < 80)}"; then
      field "Health" "${RED}${HEALTH}% — below 80%${OFF}"
      explain "Batteries under 80% typically sell for 20-40% less, or may be rejected outright. Weigh a battery replacement against the price difference before listing."
    else
      field "Health" "${GRN}${HEALTH}%${OFF}"
    fi
  else
    field "Health" "unreadable — check field names for this macOS"
  fi
  if [ -n "$BATT_COND" ]; then
    if [ "$BATT_COND" = "Normal" ]; then
      field "Apple's Condition" "${GRN}${BATT_COND}${OFF}"
    else
      field "Apple's Condition" "${YEL}${BATT_COND}${OFF}"
    fi
  fi
fi

line
printf '%s\n' "${BLD}STORAGE${OFF}"
line
field "SMART" "${SMART:-not reported}"
field "Capacity" "${CAPACITY:-not reported}"
if [ -n "$FREE_PCT" ]; then
  FLAG=""
  [ "$FREE_PCT" -lt 15 ] 2>/dev/null && FLAG="  <-- LOW, APFS degrades below ~15%"
  field "Boot volume" "${FREE_SPACE} free of ${CAPACITY} (${FREE_PCT}% free)${FLAG}"
fi

line
printf '%s\n' "${BLD}WIPE CHECK${OFF}"
line
if [ "$WIPE_STATE" = "not-wiped" ]; then
  field "Local accounts" "${RED}${USER_COUNT} found — NOT ERASED, readings above may be stale${OFF}"
  printf '%s\n' "$USERS" | while read -r u; do [ -n "$u" ] && printf '    - %s\n' "$u"; done
  explain "Erase this Mac before selling: System Settings > General > Transfer or Reset > Erase All Content and Settings. Then run this check again to confirm."
else
  field "Local accounts" "${GRN}none — appears erased${OFF}"
fi
case "$FV_STATE" in
  on)  field "FileVault" "${YEL}ON — should be OFF before resale (buyer sets their own)${OFF}" ;;
  off) field "FileVault" "${GRN}Off${OFF}" ;;
  *)   field "FileVault" "unclear: ${FV:-empty response, Terminal may need Full Disk Access}" ;;
esac
case "$SIP_STATE" in
  enabled)  field "SIP" "${GRN}enabled${OFF}" ;;
  disabled) field "SIP" "${YEL}disabled — machine was modified by a previous owner${OFF}" ;;
  *)        field "SIP" "unreadable" ;;
esac
case "$FWPW_STATE" in
  n/a)         field "Firmware password" "n/a on Apple Silicon" ;;
  set)         field "Firmware password" "${RED}SET — will block reinstall, get it from seller${OFF}"
               explain "Without the password, this Mac cannot be reinstalled or fully reset by anyone but the seller. Get it removed before buying." ;;
  not-set)     field "Firmware password" "${GRN}not set${OFF}" ;;
  *)           field "Firmware password" "unreadable (try: sudo bash mac-check.sh)" ;;
esac
if [ "$ICLOUD_STATE" = "signed-in" ]; then
  field "iCloud account" "${RED}SIGNED IN — Photos/Messages/iCloud Drive may still be present${OFF}"
  explain "Sign out before selling: Apple menu > System Settings > [your name] > Sign Out. Otherwise your personal data may still be reachable by the next owner."
else
  field "iCloud account" "${GRN}none detected${OFF}"
fi

line
printf '%s\n' "${BLD}FAULT HISTORY${OFF}"
line
if [ "$PANICS" -ge 3 ] 2>/dev/null; then
  field "Kernel panics" "${RED}${PANICS} found — repeated, suspect hardware${OFF}"
elif [ "$PANICS" -gt 0 ] 2>/dev/null; then
  field "Kernel panics" "${YEL}${PANICS} found — note only, not disqualifying${OFF}"
else
  field "Kernel panics" "${GRN}none${OFF}"
fi
[ -n "$LAST_PANIC" ] && field "Most recent" "$LAST_PANIC"

line
printf '%s\n' "${BLD}PERIPHERALS (presence only)${OFF}"
line
if [ "$CAMERA_OK" = "1" ]; then
  field "Camera" "${GRN}detected${OFF}"
else
  field "Camera" "${RED}NOT detected${OFF}"
fi
field "Wi-Fi" "${WIFI:-not reported}"
field "Graphics" "${GPU:-not reported}"
[ -n "$GPU_CORES" ] && field "GPU cores" "$GPU_CORES"
field "Display" "${RES:-no internal display detected}"
if [ "$BT_OK" = "1" ]; then
  field "Bluetooth" "${GRN}detected${OFF}"
else
  field "Bluetooth" "${RED}NOT detected${OFF}"
fi
if [ "$KBTP_OK" = "1" ]; then
  field "Keyboard/Trackpad" "${GRN}detected${OFF} (presence only — test every key/zone by hand)"
else
  field "Keyboard/Trackpad" "${RED}NOT detected — check before buying${OFF}"
fi
if [ "${PORT_COUNT:-0}" -gt 0 ] 2>/dev/null; then
  field "Thunderbolt/USB-C" "$PORT_COUNT port(s) — not tested, plug something in to verify"
else
  field "Thunderbolt/USB-C" "not reported"
fi

line
printf '%s\n' "${BLD}VERDICT${OFF}"
line
case "$VERDICT" in
  "WIPE FIRST") printf '  %s\n' "${YEL}${BLD}WIPE FIRST${OFF} — $REASON. Erase, then re-run this check." ;;
  PARTS)        printf '  %s\n' "${RED}${BLD}PARTS${OFF} — $REASON" ;;
  CHECK)        printf '  %s\n' "${YEL}CHECK MANUALLY${OFF} — battery health unreadable" ;;
  RESELL)       printf '  %s\n' "${GRN}${BLD}RESELL${OFF}" ;;
esac
line

# ── CSV LOG ─────────────────────────────────────────────────────
CSV="$(cd "$(dirname "$0")" && pwd)/mac-check-log.csv"
if [ ! -f "$CSV" ]; then
  printf 'timestamp,serial,model,model_id,model_name,chip,ram,macos,os_name,install_date,updates_available,cycles,health_pct,battery_condition,smart,capacity,free_pct,gpu_cores,activation_lock,mdm,local_accounts,filevault,icloud,panics,verdict,reason\n' > "$CSV"
fi
printf '%s,%s,"%s","%s","%s","%s","%s",%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,"%s"\n' \
  "$(date '+%Y-%m-%d %H:%M:%S')" "$SERIAL" "$MODEL" "$MODEL_ID" "$MODEL_NAME" "$CHIP" "$RAM" \
  "$OSVER" "$OS_NAME" "${INSTALL_DATE:-}" "$UPDATE_STATE" "${CYCLES:-}" "${HEALTH:-}" "${BATT_COND:-}" "${SMART:-}" "${CAPACITY:-}" "${FREE_PCT:-}" "${GPU_CORES:-}" \
  "$AL" "$MDM_STATE" "${USER_COUNT:-0}" "$FV_STATE" "$ICLOUD_STATE" "${PANICS:-0}" "$VERDICT" "$REASON" >> "$CSV"

printf '  logged to %s\n' "$CSV"
[ -f "$REPORT_FILE" ] && printf '  full report saved to %s\n' "$REPORT_FILE"

# Optional update install. Only offered when updates were actually
# found. Gated by sudo — the OS itself demands an admin password
# before anything happens, so this can't fire by accident the way a
# bare y/n keypress could for something destructive like an erase.
# Tested: read -p works correctly through the tee redirect already
# in place for the report file (confirmed on real hardware).
if [ "$UPDATE_STATE" = "available" ]; then
  echo ""
  read -p "  Install available update(s) now? Needs your admin password, may restart the Mac. [y/N]: " -r INSTALL_ANSWER
  if [[ "$INSTALL_ANSWER" =~ ^[Yy]$ ]]; then
    echo "  Installing — you'll be asked for your password. This can take a while."
    sudo /usr/sbin/softwareupdate -i -a
    echo "  Done. Run this check again to confirm the new state."
  else
    echo "  Skipped. Run 'sudo softwareupdate -i -a' manually anytime."
  fi
fi

# Clean up the saved report file — strip ANSI color codes so it's
# readable in a plain text editor, not just Terminal. This MUST be
# the absolute last action in the script and must print nothing
# afterward: testing showed that writing directly to the file while
# tee still holds it open from the live redirect corrupts it with
# null bytes if anything prints through tee after this point. Also
# testing showed nested process substitution (tee piping straight
# into a stripping sed) is separately unreliable — it silently
# failed to create the file in some runs. This two-phase approach
# (plain reliable tee, then a standalone cleanup pass) tested clean.
if [ -f "$REPORT_FILE" ]; then
  /bin/sleep 0.2
  CLEAN_REPORT=$(/usr/bin/tr -d '\033' < "$REPORT_FILE" | /usr/bin/sed 's/\[[0-9;]*m//g')
  printf '%s\n' "$CLEAN_REPORT" > "$REPORT_FILE"
fi
