#!/usr/bin/env bash
# GHOST Workstation Cloud Boot v2.0
# Non-destructive Ubuntu user-session Cloud PC launcher. Does NOT install an OS.
set -Eeuo pipefail

VERSION='2.0'
STATE_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/cpx-cloud"
AUTOSTART_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/autostart"
APP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
BIN_DIR="$HOME/.local/bin"
LAUNCHER="$BIN_DIR/cpx-cloud-launch"
AUTOSTART="$AUTOSTART_DIR/cpx-cloud.desktop"
APPENTRY="$APP_DIR/cpx-cloud.desktop"
DEFAULT_URL='https://cpx.agency/ghost/workstation/'
STAGE_FILE="$STATE_DIR/persistence-stage"
VERIFIED_FILE="$STATE_DIR/persistence-verified"

note(){ printf '\n[GHOST Workstation] %s\n' "$*"; }
fail(){ printf '\n[STOP] %s\n' "$*" >&2; exit 1; }
helptext(){ cat <<'HELP'
GHOST WORKSTATION CLOUD BOOT v2.0 — Ubuntu -> browser -> cloud desktop
Usage:
  bash CPX-GHOST-WORKSTATION.sh --check               Read-only hardware, persistence and network check
  bash CPX-GHOST-WORKSTATION.sh --launch              Open CPX GHOST Workstation portal now
  bash CPX-GHOST-WORKSTATION.sh --stage               Copy this script to mounted BOOTFORGE
  bash CPX-GHOST-WORKSTATION.sh --mark                Mark a persistent Ubuntu session for reboot test
  bash CPX-GHOST-WORKSTATION.sh --verify              Verify mark survived a REAL reboot
  bash CPX-GHOST-WORKSTATION.sh --install             Configure launch automatically after Ubuntu login
  bash CPX-GHOST-WORKSTATION.sh --url https://...     Change the launch portal (verified install only)
  bash CPX-GHOST-WORKSTATION.sh --mode app|kiosk       Choose compact app or kiosk view
  bash CPX-GHOST-WORKSTATION.sh --uninstall           Remove only this program's autostart and launcher

No commands format, repartition, or modify a disk's bootloader/BIOS.
This tool cannot install, license, or provision Windows 365 or Windows Insider.
It launches the cloud login page; you sign in normally, including MFA.
HELP
}
validate_url(){ [[ "$1" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[^[:space:]]*)?$ ]] || fail 'Only standard HTTPS cloud URLs are accepted.'; }
url(){
  local u="$DEFAULT_URL"
  if [[ -r "$STATE_DIR/url.txt" ]]; then IFS= read -r u < "$STATE_DIR/url.txt" || true; fi
  validate_url "$u"
  printf '%s\n' "$u"
}
boot_id(){ cat /proc/sys/kernel/random/boot_id 2>/dev/null || fail 'Cannot read Linux boot ID.'; }
hardware_check(){
  printf '\nGHOST Workstation v%s | %s\n' "$VERSION" "$(date -Is)"
  printf 'Model: '; cat /sys/class/dmi/id/product_name 2>/dev/null || printf 'unknown\n'
  printf '\nDisks (inspection only):\n'
  if command -v lsblk >/dev/null 2>&1; then lsblk -e7 -o NAME,SIZE,MODEL,TYPE,TRAN,FSTYPE,LABEL,MOUNTPOINTS || true; fi
  printf '\nRoot mount:\n'; findmnt -n -o SOURCE,FSTYPE,TARGET / 2>/dev/null || true
  printf '\nPersistent marker: '
  if [[ -f "$VERIFIED_FILE" ]]; then printf 'two-boot verification recorded\n';
  elif [[ -f "$STAGE_FILE" ]]; then printf 'mark created, reboot verification pending\n';
  else printf 'not verified\n'; fi
  printf 'Network: '; if command -v nmcli >/dev/null 2>&1; then nmcli -t -f DEVICE,STATE device status | grep -E ':(connected|connecting)' || printf 'no active connection reported\n'; else printf 'NetworkManager status unavailable\n'; fi
  printf 'Cloud portal: %s\n' "$(url)"
  if command -v chromium >/dev/null 2>&1 || command -v google-chrome >/dev/null 2>&1 || command -v firefox >/dev/null 2>&1; then
    printf 'Browser: present\n'
  else printf 'Browser: none detected (install a supported browser after persistence)\n'; fi
  printf 'Autostart: '; [[ -f "$AUTOSTART" ]] && printf 'installed\n' || printf 'not installed\n'
  note 'No disks or firmware were changed.'
}
launch(){
  local u mode browser
  if command -v nm-online >/dev/null 2>&1; then nm-online -q -t 18 || true; fi
  u="$(url)"; mode='app'
  [[ ! -r "$STATE_DIR/mode.txt" ]] || { IFS= read -r mode < "$STATE_DIR/mode.txt" || true; }
  [[ "$mode" == 'app' || "$mode" == 'kiosk' ]] || mode='app'
  note "Opening $u (provider authentication still required)"
  if command -v chromium >/dev/null 2>&1; then
    if [[ "$mode" == 'kiosk' ]]; then exec chromium --no-first-run --kiosk "$u";
    else exec chromium --no-first-run --app="$u"; fi
  elif command -v google-chrome >/dev/null 2>&1; then
    if [[ "$mode" == 'kiosk' ]]; then exec google-chrome --no-first-run --kiosk "$u";
    else exec google-chrome --no-first-run --app="$u"; fi
  elif command -v firefox >/dev/null 2>&1; then
    if [[ "$mode" == 'kiosk' ]]; then exec firefox --kiosk "$u";
    else exec firefox --new-window "$u"; fi
  elif command -v xdg-open >/dev/null 2>&1; then exec xdg-open "$u"
  else fail 'No browser found. Ubuntu desktop and internet need repair first.'
  fi
}
stage(){
  local mount_target='' target=''
  if mountpoint -q /mnt/cpx-ventoy 2>/dev/null; then mount_target='/mnt/cpx-ventoy'; fi
  if [[ -z "$mount_target" ]] && command -v findmnt >/dev/null 2>&1; then
    mount_target="$(findmnt -n -o TARGET -S /dev/mapper/VentoyPart 2>/dev/null | head -n 1 || true)"
  fi
  [[ -n "$mount_target" && -d "$mount_target" ]] || fail 'Existing BOOTFORGE/Ventoy data partition is not mounted. First run your existing CPX-GHOST-v3.sh --prepare, or mount the existing VentoyPart. No disks were changed.'
  [[ -w "$mount_target" ]] || fail "Cannot write to the existing USB mount: $mount_target"
  target="$mount_target/GHOST_FIELD_OPS_V3/TOOLS"
  mkdir -p "$target"
  if [[ -e "$target/CPX-GHOST-WORKSTATION.sh" ]] && ! cmp -s "$0" "$target/CPX-GHOST-WORKSTATION.sh"; then
    cp -p "$target/CPX-GHOST-WORKSTATION.sh" "$target/CPX-GHOST-WORKSTATION.sh.backup-$(date +%Y%m%d-%H%M%S)"
  fi
  cp "$0" "$target/CPX-GHOST-WORKSTATION.sh"
  chmod 0755 "$target/CPX-GHOST-WORKSTATION.sh"
  sync "$target/CPX-GHOST-WORKSTATION.sh" 2>/dev/null || sync
  note "Portable copy saved at $target/CPX-GHOST-WORKSTATION.sh"
}
mark(){
  mkdir -p "$STATE_DIR"; chmod 700 "$STATE_DIR"
  local b; b="$(boot_id)"
  printf '%s\n' "$b" > "$STAGE_FILE"
  chmod 600 "$STAGE_FILE"
  rm -f "$VERIFIED_FILE"
  note 'Marker written into the CURRENT Ubuntu home, not onto BOOTFORGE.'
  note 'Reboot, choose the same Ubuntu PERSISTENCE boot entry, then run --verify.'
  note 'Do not run --verify until AFTER a real reboot.'
}
verify(){
  [[ -f "$STAGE_FILE" ]] || fail 'Marker did not survive / was never created. Ubuntu persistence is NOT verified; do not enable autostart.'
  local old current; IFS= read -r old < "$STAGE_FILE" || true; current="$(boot_id)"
  [[ -n "$old" && "$old" != "$current" ]] || fail 'The Linux boot ID has not changed. Reboot first; verification not recorded.'
  printf 'First boot: %s\nVerified boot: %s\n' "$old" "$current" > "$VERIFIED_FILE"
  chmod 600 "$VERIFIED_FILE"
  note 'PASS: Ubuntu home settings survived a reboot. Cloud autostart can now be installed.'
}
require_verified(){ [[ -r "$VERIFIED_FILE" ]] || fail 'Persistence not proven. Run --mark, reboot into the persistent Ubuntu entry, then --verify.'; }
install(){
  require_verified
  mkdir -p "$BIN_DIR" "$AUTOSTART_DIR" "$APP_DIR" "$STATE_DIR"
  chmod 700 "$STATE_DIR"
  if [[ -e "$LAUNCHER" ]] && ! grep -q '^# CPX-HP-CLOUD-BOOT GENERATED LAUNCHER$' "$LAUNCHER"; then fail "Refusing to replace unrecognized file $LAUNCHER"; fi
  for entry in "$AUTOSTART" "$APPENTRY"; do
    if [[ -e "$entry" ]] && ! grep -q '^X-CPX-Cloud-Boot=1$' "$entry"; then fail "Refusing to replace unrecognized desktop entry $entry"; fi
  done
  cat > "$LAUNCHER" <<'SCRIPT'
#!/usr/bin/env bash
# CPX-HP-CLOUD-BOOT GENERATED LAUNCHER
set -euo pipefail
STATE_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/cpx-cloud"
U='https://cpx.agency/ghost/workstation/'
if [[ -r "$STATE_DIR/url.txt" ]]; then IFS= read -r U < "$STATE_DIR/url.txt" || true; fi
[[ "$U" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[^[:space:]]*)?$ ]] || exit 2
MODE=app
if command -v nm-online >/dev/null 2>&1; then nm-online -q -t 18 || true; fi
if [[ -r "$STATE_DIR/mode.txt" ]]; then IFS= read -r MODE < "$STATE_DIR/mode.txt" || true; fi
[[ "$MODE" == app || "$MODE" == kiosk ]] || MODE=app
if command -v chromium >/dev/null 2>&1; then
  if [[ "$MODE" == kiosk ]]; then exec chromium --no-first-run --kiosk "$U"; else exec chromium --no-first-run --app="$U"; fi
elif command -v google-chrome >/dev/null 2>&1; then
  if [[ "$MODE" == kiosk ]]; then exec google-chrome --no-first-run --kiosk "$U"; else exec google-chrome --no-first-run --app="$U"; fi
elif command -v firefox >/dev/null 2>&1; then
  if [[ "$MODE" == kiosk ]]; then exec firefox --kiosk "$U"; else exec firefox --new-window "$U"; fi
elif command -v xdg-open >/dev/null 2>&1; then exec xdg-open "$U"; fi
exit 1
SCRIPT
  chmod 700 "$LAUNCHER"
  # Desktop entry format accepts a quoted absolute executable path.
  for entry in "$AUTOSTART" "$APPENTRY"; do
    if [[ -e "$entry" ]] && ! grep -q '^X-CPX-Cloud-Boot=1$' "$entry"; then fail "Refusing to replace unrecognized desktop entry $entry"; fi
    cat > "$entry" <<ENTRY
[Desktop Entry]
Version=1.0
Type=Application
Name=GHOST Workstation
Comment=Secure browser access to remote Windows desktop
Exec="$LAUNCHER"
Terminal=false
Icon=computer
Categories=Network;RemoteAccess;
X-GNOME-Autostart-enabled=true
X-CPX-Cloud-Boot=1
ENTRY
  done
  if [[ ! -e "$STATE_DIR/url.txt" ]]; then
    printf '%s\n' "$DEFAULT_URL" > "$STATE_DIR/url.txt"
  elif grep -qx 'https://windows.cloud.microsoft' "$STATE_DIR/url.txt"; then
    cp -p "$STATE_DIR/url.txt" "$STATE_DIR/url.txt.pre-ghost"
    printf '%s\n' "$DEFAULT_URL" > "$STATE_DIR/url.txt"
  fi
  [[ -f "$STATE_DIR/mode.txt" ]] || printf 'app\n' > "$STATE_DIR/mode.txt"
  chmod 600 "$STATE_DIR/url.txt" "$STATE_DIR/mode.txt"
  note 'Cloud launcher installed into your persistent Ubuntu USER account.'
  note 'It opens the CPX workstation portal after login; no OS, VM or provider sign-in is bypassed.'
  note 'Test it now with --launch, then reboot into the SAME persistent Ubuntu entry.'
}
change_url(){
  require_verified
  validate_url "$1"
  mkdir -p "$STATE_DIR"; chmod 700 "$STATE_DIR"
  printf '%s\n' "$1" > "$STATE_DIR/url.txt"; chmod 600 "$STATE_DIR/url.txt"
  note "Default portal changed to $1"
}
mode(){
  require_verified
  [[ "$1" == app || "$1" == kiosk ]] || fail 'Mode must be app or kiosk.'
  mkdir -p "$STATE_DIR"; chmod 700 "$STATE_DIR"
  printf '%s\n' "$1" > "$STATE_DIR/mode.txt"; chmod 600 "$STATE_DIR/mode.txt"
  note "Window mode set to $1. Kiosk mode can interfere with sign-in popups; choose app if that happens."
}
uninstall(){
  if [[ -r "$LAUNCHER" ]] && grep -q '^# CPX-HP-CLOUD-BOOT GENERATED LAUNCHER$' "$LAUNCHER"; then rm -- "$LAUNCHER"; fi
  for entry in "$AUTOSTART" "$APPENTRY"; do
    if [[ -r "$entry" ]] && grep -q '^X-CPX-Cloud-Boot=1$' "$entry"; then rm -- "$entry"; fi
  done
  note 'Removed only CPX Cloud autostart and launcher. Data and boot media were not altered.'
}

[[ ${EUID:-$(id -u)} -ne 0 ]] || fail 'Run as the ordinary Ubuntu user, NOT with sudo.'
case "${1:-}" in
  --help|-h) helptext;;
  --status) hardware_check;;
  --check) hardware_check;;
  --launch) launch;;
  --stage) stage;;
  --mark) mark;;
  --verify) verify;;
  --install) install;;
  --url) [[ $# -eq 2 ]] || fail 'Pass exactly one HTTPS URL.'; change_url "$2";;
  --mode) [[ $# -eq 2 ]] || fail 'Pass app or kiosk.'; mode "$2";;
  --uninstall) uninstall;;
  *) helptext; exit 2;;
esac