#!/usr/bin/env bash
# GHOST Workstation / Ubuntu Hardware & Boot Diagnostic 2.1
# Inspection only. No sudo, network calls, disk writes, firmware changes, or account access.
set -uo pipefail
export LC_ALL=C

VERSION='2.1'
line() { printf '\n%s\n' "=============================================================="; }
section() { line; printf '%s\n' "$1"; line; }
flag() { printf '%s\n' "  $1"; }
have() { command -v "$1" >/dev/null 2>&1; }

case "${1:-}" in
  ''|--check) ;;
  --help|-h)
    cat <<'HELP'
GHOST Workstation / Ubuntu Hardware & Boot Diagnostic 2.1
Usage: bash GHOST-UBUNTU-DIAGNOSTIC.sh [--check|--help]
Optional local report: bash GHOST-UBUNTU-DIAGNOSTIC.sh | tee GHOST-REPORT.txt
This is READ ONLY: no sudo, network access, changes, or identity collection.
The report omits usernames, serial numbers, IP/MAC addresses and drive UUIDs.
HELP
    exit 0 ;;
  *) printf 'Unknown option: %s\n' "$1" >&2; exit 2 ;;
esac

printf 'GHOST / UBUNTU FIELD DIAGNOSTIC v%s\n' "$VERSION"
printf 'Run from the HP Ubuntu desktop as the regular user.\n'
printf 'No changes will be made to the HP or the SanDisk.\n'

section '1 / DEVICE, BOOT ENVIRONMENT'
model=$(cat /sys/class/dmi/id/product_name 2>/dev/null || true)
bios=$(cat /sys/class/dmi/id/bios_version 2>/dev/null || true)
flag "Model: ${model:-unknown}"
flag "BIOS version: ${bios:-unknown}"
flag "Kernel: $(uname -r)"
if [[ -r /etc/os-release ]]; then
  os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release | head -n1 | tr -d '"')
  flag "OS: ${os:-unknown}"
fi
if [[ -d /sys/firmware/efi ]]; then
  is_uefi=1; flag 'Firmware boot: UEFI'
else
  is_uefi=0; flag 'Firmware boot: Legacy/unknown'
fi
root_fs=$(findmnt -n -o FSTYPE -T / 2>/dev/null | head -n1 || true)
flag "Root filesystem type: ${root_fs:-unknown}"
if [[ "$root_fs" == overlay || -d /rofs || -e /cdrom/casper || -d /run/live ]]; then
  live_env=1; flag 'Live Ubuntu indicators: DETECTED (settings may reset on reboot)'
else
  live_env=0; flag 'Live Ubuntu indicators: not detected (persistence still needs verification)'
fi

section '2 / PHYSICAL STORAGE AND PARTITIONS (NO SERIALS)'
if have lsblk; then
  lsblk -e7 -o NAME,SIZE,TYPE,TRAN,RM,FSTYPE,MODEL -n 2>/dev/null || true
else
  flag 'lsblk unavailable; installable tools are intentionally not changed.'
fi
internal_found=0; nvme_disk=0; win_parts=0; internal_names=''
if have lsblk; then
  while read -r dev type tran removable; do
    [[ "$type" == disk ]] || continue
    [[ "$dev" == /dev/* ]] || continue
    [[ "$tran" == usb || "$removable" == 1 ]] && continue
    internal_found=$((internal_found+1))
    internal_names="$internal_names $dev"
    [[ "$dev" == /dev/nvme*n* ]] && nvme_disk=$((nvme_disk+1))
    while read -r fstype; do
      case "${fstype,,}" in
        ntfs|bitlocker) win_parts=$((win_parts+1)) ;;
      esac
    done < <(lsblk -nr -o FSTYPE "$dev" 2>/dev/null || true)
  done < <(lsblk -dnpo NAME,TYPE,TRAN,RM 2>/dev/null || true)
fi
flag "Internal non-USB disks visible: $internal_found"
flag "Internal NVMe disks visible: $nvme_disk"
flag "Windows-compatible NTFS/BitLocker volumes on internal disks: $win_parts"

section '3 / NVME CONTROLLERS AND DRIVER ENUMERATION'
nvme_sys=0
for p in /sys/class/nvme/nvme[0-9]*; do [[ -e "$p" ]] && nvme_sys=$((nvme_sys+1)); done
flag "NVMe controllers initialized by Linux: $nvme_sys"
pci_nvme=0; pci_vmd=0; pci_sata=0
if have lspci; then
  controllers=$(lspci -nn 2>/dev/null | grep -Ei 'NVMe|Non-Volatile|VMD|RAID|SATA|Mass storage|Storage controller' || true)
  if [[ -n "$controllers" ]]; then
    printf '%s\n' "$controllers"
    pci_nvme=$(printf '%s\n' "$controllers" | grep -Eic 'NVMe|Non-Volatile' || true)
    pci_vmd=$(printf '%s\n' "$controllers" | grep -Eic 'VMD|RAID' || true)
    pci_sata=$(printf '%s\n' "$controllers" | grep -Eic 'SATA|AHCI' || true)
  else
    flag 'No matching PCI storage controllers in lspci output.'
  fi
else
  flag 'lspci not installed (PCI status unknown; NOT proof of SSD failure).'
fi
flag "PCI NVMe entries: $pci_nvme / VMD or RAID entries: $pci_vmd / SATA entries: $pci_sata"
if have lsmod; then
  flag 'Loaded related drivers (a built-in driver may not appear):'
  lsmod 2>/dev/null | awk '$1 ~ /^(nvme|nvme_core|vmd|ahci)$/ {print "  " $1}'
fi

section '4 / EFI BOOT MANAGER & NETWORK BOOT INDICATORS'
windows_entry=0; network_entry=0
if [[ $is_uefi -eq 1 ]] && have efibootmgr; then
  entries=$(efibootmgr 2>/dev/null | grep '^Boot[0-9A-Fa-f]\{4\}' || true)
  if [[ -n "$entries" ]]; then
    # Boot numbers + a short, coarse label classification only: no EFI paths or UUIDs.
    while IFS= read -r ent; do
      case "${ent,,}" in
        *windows*boot*manager*) windows_entry=$((windows_entry+1)) ;;
        *pxe*|*ipv4*|*ipv6*|*network*) network_entry=$((network_entry+1)) ;;
      esac
    done <<< "$entries"
    flag "Windows Boot Manager entries: $windows_entry"
    flag "PXE/network boot entries: $network_entry"
  else
    flag 'No EFI boot labels accessible without elevated permissions.'
  fi
else
  flag 'EFI entry check unavailable (UEFI mode or efibootmgr missing).'
fi
if have nmcli; then
  net=$(nmcli -t -f STATE general status 2>/dev/null | head -n1 || true)
  flag "NetworkManager: ${net:-status unavailable} (no network identifiers displayed)"
fi

section '5 / EVIDENCE-BASED TRIAGE'
if (( nvme_disk > 0 )); then
  flag 'RESULT: Internal NVMe storage is VISIBLE to Ubuntu.'
  if (( win_parts > 0 || windows_entry > 0 )); then
    flag 'ACTION: A Windows volume or boot entry may be recoverable.'
    flag 'Preserve contents and BitLocker recovery key. Check EFI/Windows repair before reinstalling.'
  else
    flag 'ACTION: Inspect internal partitions and backups before creating any new Windows installation.'
  fi
elif (( internal_found > 0 )); then
  flag 'RESULT: Internal non-USB storage exists, but no NVMe disk was recognized.'
  flag 'ACTION: Determine whether this is SATA storage or a controller/driver visibility issue.'
elif (( pci_nvme > 0 || nvme_sys > 0 )); then
  flag 'RESULT: NVMe controller is visible but its usable disk namespace is MISSING.'
  flag 'ACTION: Run HP Esc > F2 storage test. A controller may be present while the SSD is inaccessible.'
  flag 'ACTION: Preserve the device. Investigate NVMe initialization, firmware, or failing media.'
elif (( pci_vmd > 0 )); then
  flag 'RESULT: A VMD/RAID storage controller is visible, but no internal disk is enumerated.'
  flag 'ACTION: Check driver support and firmware settings; DO NOT switch RAID/VMD modes blindly.'
else
  flag 'RESULT: No internal boot disk detected by this Linux session.'
  flag 'ACTION: Reboot > Esc > F2 > Component Tests > Storage/SSD Test.'
  flag 'If HP firmware also cannot detect it: SSD/connection/motherboard repair is required.'
  flag 'If HP firmware detects it: investigate firmware storage mode or driver compatibility.'
fi
if (( live_env == 1 )); then
  flag 'CAUTION: This is a live environment; installing an autostart script may not survive reboot.'
fi
if (( network_entry == 0 )); then
  flag 'Network boot capability is NOT proven by this diagnostic.'
else
  flag 'Network entry exists, but a working UEFI NIC and PXE server must still be validated.'
fi
flag 'Windows 11 local startup requires a working internal boot disk or a tested alternative firmware boot path.'
flag 'Cloud/VM access begins only AFTER a local OS or network-loaded thin client has booted.'

section '6 / NEXT STEP'
flag 'Copy the section 5 RESULT and the sections 2-4 into this chat.'
flag 'Separately report the HP Esc > F2 Storage test result (PASS, FAIL/Failure ID, or NOT DETECTED).'
flag 'Do NOT erase or repartition the SanDisk, disable disk encryption, or reset firmware.'
flag 'No serial numbers, usernames, passwords, MAC/IP addresses or drive UUIDs were collected.'