#!/usr/bin/env bash
# =============================================================================
# NerdZap DeckVM for Steam Deck (SteamOS desktop mode)
#
# Runs a real Windows inside a virtual machine on your Steam Deck (dockur/windows,
# QEMU + KVM, Podman). Windows itself runs in normal user mode, so it needs NO password.
# The password is only asked when you hand a USB device (e.g. a controller) to Windows,
# because that part needs administrator rights. Menu driven. Windows itself is downloaded by dockur
# while you wait; nothing from Microsoft is bundled here.
#
# Built-in guided job: update an Xbox controller's firmware without a Windows PC.
# That job passes the controller's USB port into the VM and keeps it attached while
# the controller resets itself during the update.
#
# Credit: the udev relay and the port-passthrough approach come from
# https://github.com/zedxter/xbox-firmware-linux (MIT, Copyright (c) 2026 zedxter).
#
# Usage:  bash deckvm.sh            (menu)
#         bash deckvm.sh help       (commands)
# Everything is logged under  ~/deckvm/logs  (use "Make a report" if stuck).
# =============================================================================
set -uo pipefail

BUILD="60"   # bump with every build: shown in About, reports and logs as (live60)
TOOL_VERSION="1.0.0 (live${BUILD})"

BASE="${DECKVM_BASE:-$HOME/deckvm}"
STORAGE="$BASE/storage"        # the Windows disk lives here
PODROOT="$BASE/podman"         # administrator-mode container store (USB sessions only): in /home, NOT in the tiny /var partition
PODRUN="/run/deckvm-podman"
PODROOT_U="$BASE/podman-user"  # normal-user container store (plain Windows, no password)
PODRUN_U="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/deckvm-podman"
RUNTIME="$BASE/runtime"        # holds the empty udev "control" marker mounted into the container
OEM="$BASE/oem"                # copied into Windows as C:\OEM; install.bat runs once, at the end of install
SHARED="$BASE/shared"          # appears in Windows as drive Z: (and "Shared" on the desktop)
LOGS="$BASE/logs"
CONF="$BASE/config.env"
STATE="$BASE/state.env"
RELAY="$BASE/relay.py"
USBCAP="$BASE/usbcap.py"
EVENTS="$LOGS/events.log"
PIDFILE="$BASE/bg.pids"
SYSFS="${DECKVM_SYSFS:-/sys/bus/usb/devices}"

NAME="deckvm"
# A tested image digest goes here before a public release (for example sha256:1a2b...). Empty means the newest image.
DOCKUR_PIN=""
if [[ -n "$DOCKUR_PIN" ]]; then IMAGE_DEFAULT="docker.io/dockurr/windows@$DOCKUR_PIN"; else IMAGE_DEFAULT="docker.io/dockurr/windows:latest"; fi
IMAGE="${DECKVM_IMAGE:-$IMAGE_DEFAULT}"
BOOT_ID="$(cat /proc/sys/kernel/random/boot_id 2>/dev/null || echo unknown)"
MONSOCK="/run/shm/monitor.sock"
USBDEV_ID="deckvm-usb"
# Touch-aware display: the Windows container also publishes its remote-desktop (RDP) port on 127.0.0.1 only, and a small
# helper container (guacd, from the Apache Guacamole project) turns RDP into a web display that passes touch to Windows.
GUACD_IMAGE="${DECKVM_GUACD_IMAGE:-docker.io/guacamole/guacd:1.6.0}"
GUACD_NAME="deckvm-guacd"
RDP_PORT=33890
GUACD_PORT=48220
touch_on() { [[ "${NO_TOUCH_THIS_START:-0}" != 1 && "${DECKVM_TOUCH:-${TOUCH:-0}}" == 1 ]]; }   # the touch display (RDP + helper) is opt-in: Settings > Touch display
RDP_PUBLISHED=0

MODCONF_RUN=/run/deckvm-modprobe.conf
MODCONF_ETC=/etc/modprobe.d/zz-deckvm.conf
GUI_PY="$BASE/gui.py"
GUI_INFO="$BASE/gui.json"          # {pid, port, token} of the running local GUI server
GUI_PENDING="$BASE/gui-pending.json"
ASKPASS="$BASE/askpass.sh"         # graphical password prompt for sudo (GUI mode)
UI_SKIP="$BASE/ui-skip-replug"      # the GUI's "Skip" button on the replug screen creates this file
UI_CONTINUE="$BASE/ui-continue"    # the GUI's "I can see the desktop" button creates this file
STAGEFILE="$BASE/stage"
# GUI mode: the local web GUI runs the engine with these set, so nothing ever waits for the keyboard
GUI="${DECKVM_GUI:-0}"
NONINT="${DECKVM_NONINTERACTIVE:-0}"
LAUNCHER="$HOME/.local/bin/deckvm"
DESKTOP_FILE="$HOME/Desktop/DeckVM.desktop"
APP_FILE="$HOME/.local/share/applications/DeckVM.desktop"   # lets the desktop match the DeckVM window to its own icon and name
DEFAULT_WIN="deckvm"            # the Windows user name and password of a new install: short on purpose, it is typed on a lock screen

# Windows editions offered by dockur. Format: code|name|sizeGB|note
EDITIONS=(
  "11|Windows 11 Pro|8|Full Windows 11 from Microsoft, with the Microsoft Store. The most complete and compatible choice."
  "11l|Windows 11 LTSC|5|A plainer Windows 11 for long-term use. Leaves out the Microsoft Store and most bundled apps."
  "tiny11|Tiny11|5|An unofficial, slimmed-down Windows 11 with the extras removed. Lighter to run, and keeps the Microsoft Store."
  "core11|Tiny11 Core|3|An unofficial, heavily cut-down Windows 11. Very small and fine for simple apps, but expect compatibility problems with others."
  "10|Windows 10 Pro|6|Full Windows 10 from Microsoft. Older, and Microsoft no longer supports it, so newer apps may not run."
  "10l|Windows 10 LTSC|5|A plainer Windows 10 for long-term use. Leaves out the Microsoft Store and most bundled apps."
  "tiny10|Tiny10|4|An unofficial, slimmed-down Windows 10 with the extras removed. Lighter to run."
)

FAILS=0
WARNS=0

# ---------------------------------------------------------------- helpers ----
IS_TTY=0
[[ -t 1 && "$GUI" != 1 ]] && IS_TTY=1
c() { [[ $IS_TTY == 1 ]] && printf '\033[%sm' "$1"; return 0; }

ts()    { date '+%Y-%m-%d %H:%M:%S'; }
dbg()   { [[ "${NOLOG:-0}" == 1 ]] && return 0; mkdir -p "$LOGS" 2>/dev/null; printf '[%s] %s\n' "$(ts)" "$*" >> "$LOGS/detail.log"; }
say()   { echo "$*"; }
step()  { echo; c 1; echo "> $*"; c 0; dbg "STEP $*"; }
ok()    { c 32; printf '  [ OK ] '; c 0; echo "$*"; dbg "OK $*"; }
info()  { echo "         $*"; dbg "INFO $*"; }
warn()  { c 33; printf '  [WARN] '; c 0; echo "$*"; dbg "WARN $*"; WARNS=$((WARNS+1)); }
fail()  { c 31; printf '  [FAIL] '; c 0; echo "$*"; dbg "FAIL $*"; FAILS=$((FAILS+1)); }
die()   { fail "$*"; [[ -n "${USB_ROLLBACK:-}" && "$BASHPID" == "$$" ]] && usb_rollback
  echo; echo "  Something went wrong. Choose 'Make a report' in the menu (or run: bash deckvm.sh report)"; echo "  and send me the file it creates."; exit 1; }

event() { # event NAME detail...  -> timeline used by the report
  local name="$1"; shift
  mkdir -p "$LOGS"
  printf '%s\t%s\t%s\n' "$(ts)" "$name" "$*" >> "$EVENTS"
  dbg "EVENT $name: $*"
}

SUDO=(sudo)
[[ $EUID -eq 0 ]] && SUDO=()

mask() { local s="$*"; [[ -n "${WIN_PASS:-}" && "${WIN_PASS}" != nerdzap && "${WIN_PASS}" != "$DEFAULT_WIN" ]] && s="${s//$WIN_PASS/***}"; printf '%s' "$s"; }

runq() { # run quietly: command line and exit code go to the detail log, output to commands.log
  dbg "RUN: $(mask "$*")"
  "$@" >> "$LOGS/commands.log" 2>&1
  local rc=$?
  dbg "EXIT($rc): $(mask "${*:1:4}")"
  return $rc
}

# Two engines: "user" = rootless Podman (no password, used for plain Windows) and "root" = administrator-mode Podman
# (only for USB passthrough, which needs root). ENGINE is the one pm() talks to; BASE_ENGINE is the normal one
# (root only as a fallback when rootless Podman is not usable on this system).
BASE_ENGINE=user
ENGINE=user
pm_u() { podman --root "$PODROOT_U" --runroot "$PODRUN_U" "$@"; }
pm_r() { "${SUDO[@]}" podman --root "$PODROOT" --runroot "$PODRUN" "$@"; }
pm() { if [[ "$ENGINE" == root ]]; then pm_r "$@"; else pm_u "$@"; fi; }
pmg() { if [[ "$BASE_ENGINE" == root ]]; then pm_r "$@"; else pm_u "$@"; fi; }   # the touch-display helper always uses the normal engine
# The same as an argv array for background jobs (nohup cannot run shell functions)
PMV=()
set_pmv() {
  if [[ "$ENGINE" == root ]]; then PMV=(sudo -n podman --root "$PODROOT" --runroot "$PODRUN")
  else PMV=(podman --root "$PODROOT_U" --runroot "$PODRUN_U"); fi
  [[ $EUID -eq 0 ]] && PMV=(podman --root "$PODROOT" --runroot "$PODRUN")
  return 0
}

STAGE_T0=0
STAGE_NAME=""
stage_begin() { STAGE_NAME="$1"; STAGE_T0=$(date +%s); event "CHECKPOINT" "begin: $1"; }
stage_end()   { local d=$(( $(date +%s) - STAGE_T0 )); event "CHECKPOINT" "end: ${STAGE_NAME:-?} rc=${1:-0} seconds=$d"; }

# Interactive input always comes from the keyboard, so this also works as: curl ... | bash
ask() { # ask "prompt" [default]  -> sets REPLY
  local p="$1" d="${2:-}"
  if [[ "$NONINT" == 1 ]]; then REPLY="$d"; return 0; fi
  if [[ -n "$d" ]]; then read -r -p "$p [$d] " REPLY </dev/tty || REPLY=""; REPLY="${REPLY:-$d}"
  else read -r -p "$p " REPLY </dev/tty || REPLY=""; fi
}
confirm() { # confirm "question" [y|n default]
  local def="${2:-n}" hint="y/N"
  if [[ "$NONINT" == 1 ]]; then [[ "${DECKVM_YES:-0}" == 1 || "$def" == y ]]; return; fi
  [[ "$def" == y ]] && hint="Y/n"
  ask "$1 ($hint)" ""
  [[ -z "$REPLY" ]] && REPLY="$def"
  [[ "$REPLY" == [yY]* ]]
}
pause() { [[ "$NONINT" == 1 ]] && return 0; read -r -p "${1:-Press Enter to continue...}" _ </dev/tty || true; }

write_askpass() { # a graphical password prompt, so the GUI never has to see the password
  mkdir -p "$BASE"
  cat > "$ASKPASS" <<'ASKEOF'
#!/usr/bin/env bash
# Pressing Cancel (or sending nothing) leaves a marker, so sudo's repeat attempts stop at once and DeckVM can tell a
# cancel from a wrong password.
mark="${DECKVM_ASK_MARK:-}"
[[ -n "$mark" && ( -e "$mark" || -e "$mark.empty" ) ]] && exit 1
msg="Your Steam Deck password is needed ${DECKVM_ASK_REASON:-for DeckVM}. Windows itself does not need it."
wf="$(dirname "$0")/askpass.waiting"          # tells the DeckVM window a password box is open, so it keeps its own text out of the way
printf '%s' "${DECKVM_ASK_REASON:-for DeckVM}" > "$wf" 2>/dev/null
trap 'rm -f "$wf"' EXIT
if command -v kdialog >/dev/null 2>&1; then pw="$(kdialog --title "DeckVM" --password "$msg")"; rc=$?
elif command -v zenity >/dev/null 2>&1; then pw="$(zenity --password --title="DeckVM")"; rc=$?
else exit 1
fi
if [[ $rc -ne 0 ]]; then [[ -n "$mark" ]] && : > "$mark"; exit 1; fi
if [[ -z "$pw" ]]; then [[ -n "$mark" ]] && : > "$mark.empty"; exit 1; fi
printf '%s\n' "$pw"
ASKEOF
  chmod 700 "$ASKPASS"
}
ASK_MARK="$BASE/askpass.cancelled"
# In the window every sudo call may need a password dialog (never a prompt nobody can see), so they all use the dialog.
if [[ "$GUI" == 1 && $EUID -ne 0 ]]; then SUDO=(sudo -A); export SUDO_ASKPASS="$ASKPASS" DECKVM_ASK_MARK="$ASK_MARK"; fi
REQDIR="$RUNTIME/req"   # requests to the session helper (the watchdog): empty files named after the job
# The person pressed Cancel in the password box: stop quietly, undo what a USB start had changed, exit code 130.
cancelled_exit() {
  rm -f "$ASK_MARK"
  say "  Cancelled. Nothing was changed."
  event "CANCELLED" "password box closed"
  [[ -n "${USB_ROLLBACK:-}" && "$BASHPID" == "$$" ]] && usb_rollback
  exit 130
}
need_sudo() { # need_sudo ["what it is for"]
  if sudo -n true 2>/dev/null; then return 0; fi
  if [[ "$GUI" == 1 ]]; then
    write_askpass
    rm -f "$ASK_MARK" "$ASK_MARK.empty"
    SUDO_ASKPASS="$ASKPASS" DECKVM_ASK_MARK="$ASK_MARK" DECKVM_ASK_REASON="${1:-}" sudo -A -v 2>>"$LOGS/commands.log" \
      || { [[ -e "$ASK_MARK" ]] && cancelled_exit
           [[ -e "$ASK_MARK.empty" ]] && { rm -f "$ASK_MARK.empty"; die "Your Deck does not have a password yet. Open Konsole, type: passwd   set one, then try again."; }
           die "The password was not accepted. Try again, or set one in a terminal with 'passwd' first."; }
    return 0
  fi
  say "  Your Steam Deck password is needed ${1:-for this step} (the one you set with 'passwd'). Windows itself does not need it."
  say "  Nothing shows while you type it. That is normal."
  sudo -v || die "sudo failed. If you never set a password, open a terminal, run 'passwd', then try again."
}
need_sudo_quiet() {
  sudo -n true 2>/dev/null && return 0
  if [[ "$GUI" == 1 ]]; then write_askpass; rm -f "$ASK_MARK"; SUDO_ASKPASS="$ASKPASS" DECKVM_ASK_MARK="$ASK_MARK" sudo -A -v 2>/dev/null; return; fi
  [[ -t 0 || -r /dev/tty ]] && sudo -v 2>/dev/null
}

load_conf() {
  [[ -f "$CONF" ]] || return 1
  # shellcheck disable=SC1090
  source "$CONF"
}
save_conf() { # save_conf KEY VALUE
  mkdir -p "$BASE"
  ( umask 077
    touch "$CONF"
    grep -v "^$1=" "$CONF" > "$CONF.tmp" 2>/dev/null || true
    printf '%s=%q\n' "$1" "$2" >> "$CONF.tmp"
    mv "$CONF.tmp" "$CONF" )
}
save_state() { # save_state KEY VALUE (replace existing key)
  mkdir -p "$BASE"
  touch "$STATE"
  grep -v "^$1=" "$STATE" > "$STATE.tmp" 2>/dev/null || true
  printf '%s=%q\n' "$1" "$2" >> "$STATE.tmp"
  mv "$STATE.tmp" "$STATE"
}
# shellcheck disable=SC1090
# State about an administrator-mode (USB) session belongs to one boot of the Deck: a restart ends the container and the
# kernel loads its drivers again. A session that ended by itself (the watchdog gave the devices back) leaves a marker.
load_state() {
  [[ -f "$STATE" ]] && source "$STATE"
  local stale=0
  if [[ -n "${ACTIVE_BOOT:-}" && "$ACTIVE_BOOT" != "$BOOT_ID" ]]; then stale=1; fi
  if [[ -e "$RUNTIME/restored" ]]; then stale=1; rm -f "$RUNTIME/restored" 2>/dev/null; fi
  if [[ $stale == 1 ]] && { [[ -n "${ACTIVE_ENGINE:-}" ]] || [[ -n "${HOST_MODS_UNLOADED:-}" ]]; }; then
    ACTIVE_ENGINE=""; HOST_MODS_UNLOADED=""; ACTIVE_BOOT=""
    if [[ $EUID -ne 0 && -w "$BASE" ]]; then save_state ACTIVE_ENGINE ""; save_state HOST_MODS_UNLOADED ""; save_state ACTIVE_BOOT ""; fi
  fi
  return 0
}

# Is a kernel module loaded? (awk reads all input; "lsmod | grep -q" can die of SIGPIPE under pipefail)
mod_loaded() { lsmod | awk -v m="$1" '$1==m {f=1} END{exit !f}'; }
# Busy = any socket of ours on that local port, whatever its state (a root-engine container's published port shows
# up as UNCONN, not LISTEN). Closed connections waiting out their timer (TIME-WAIT) do not count.
port_busy() { ss -tan 2>/dev/null | awk -v p=":$1" '$1 != "State" && $1 != "TIME-WAIT" && $4 ~ (p "$") {f=1} END{exit !f}'; }
free_gb() { df -BG --output=avail "$1" 2>/dev/null | tail -1 | tr -dc '0-9'; }

# ------------------------------------------------------------ edition table ----
edition_field() { # edition_field CODE FIELD(1-5)
  local e
  for e in "${EDITIONS[@]}"; do
    [[ "${e%%|*}" == "$1" ]] && { printf '%s' "$e" | cut -d'|' -f"$2"; return 0; }
  done
  return 1
}
edition_name() { edition_field "$1" 2 || printf 'Windows (%s)' "$1"; }

# --------------------------------------------------------------------- USB ----
# Lists USB devices: "<port> <vid:pid> <product>". Default mode skips hubs and the Deck's own internal parts;
# "all" skips only hubs (used for Xbox controllers and the watchers, where a wrong "internal" guess would hide the device).
list_usb() {
  local mode="${1:-ext}" d name vid cls rem
  for d in "$SYSFS"/*; do
    [[ -r "$d/idVendor" ]] || continue
    name="$(basename "$d")"
    [[ $name =~ ^[0-9]+-[0-9]+(\.[0-9]+)*$ ]] || continue
    vid="$(<"$d/idVendor")"
    cls="$(cat "$d/bDeviceClass" 2>/dev/null || echo 00)"
    [[ "$cls" == "09" ]] && continue          # hubs
    if [[ "$mode" == ext ]]; then
      rem="$(cat "$d/removable" 2>/dev/null || echo unknown)"
      [[ "$rem" == "fixed" ]] && continue     # built into the Deck
      [[ "$vid" == "28de" ]] && continue      # Valve: the Deck's own controls
    fi
    echo "$name $vid:$(<"$d/idProduct") $(cat "$d/product" 2>/dev/null || echo '?')"
  done
}
list_ms() { list_usb all | awk '$2 ~ /^045e:/'; }

# Which HOST kernel driver(s) are bound to a USB port's interfaces? (xbox-gip / xpad / usbfs when QEMU owns it)
host_driver_of() {
  local port="$1" i d out=""
  for i in "$SYSFS/$port":*; do
    [[ -e "$i/driver" ]] || continue
    d="$(basename "$(readlink -f "$i/driver")")"
    out+="$d
"
  done
  printf '%s' "$out" | sort -u | tr '\n' ' ' | sed 's/ $//'
  [[ -n "$out" ]] || printf 'none'
}

# Keep the host's Xbox drivers from re-binding while Windows owns the controller. The file goes where udev already
# looks (/etc/modprobe.d, as a symlink to a /run file so a reboot always clears it) and uses 'install ... /bin/false',
# which blocks explicit modprobe calls as well as alias loading.
block_host_drivers() {
  printf '# NerdZap DeckVM (temporary)\nblacklist xpad\nblacklist xbox_gip\nblacklist xbox-gip\ninstall xpad /bin/false\ninstall xbox_gip /bin/false\ninstall xbox-gip /bin/false\n' \
    | "${SUDO[@]}" tee "$MODCONF_RUN" >/dev/null
  local newdir=0
  [[ -d /etc/modprobe.d ]] || newdir=1
  if "${SUDO[@]}" mkdir -p /etc/modprobe.d && "${SUDO[@]}" ln -sf "$MODCONF_RUN" "$MODCONF_ETC"; then
    dbg "driver block installed: $MODCONF_ETC -> $MODCONF_RUN"
  else
    warn "Could not write /etc/modprobe.d (read-only?). Using /run/modprobe.d instead."
    "${SUDO[@]}" mkdir -p /run/modprobe.d && "${SUDO[@]}" cp "$MODCONF_RUN" /run/modprobe.d/deckvm.conf
    newdir=1
  fi
  "${SUDO[@]}" udevadm control --reload 2>/dev/null || true
  [[ $newdir == 1 ]] && { "${SUDO[@]}" systemctl restart systemd-udevd 2>/dev/null || warn "could not restart systemd-udevd"; }
  return 0
}
unblock_host_drivers() {
  "${SUDO[@]}" rm -f "$MODCONF_ETC" "$MODCONF_RUN" /run/modprobe.d/deckvm.conf
  "${SUDO[@]}" udevadm control --reload 2>/dev/null || true
}

# Pick a USB device. Sets PORT, DEV_ID (vid:pid), DEV_NAME. Arg 1 = "xbox" restricts to Microsoft devices.
pick_usb() {
  local mode="${1:-any}" lines count
  if [[ "$mode" == xbox ]]; then lines="$(list_ms)"; else lines="$(list_usb)"; fi
  count=$(printf '%s\n' "$lines" | grep -c . || true)
  if [[ -n "${DECKVM_USB_PORT:-}" ]]; then
    [[ "$DECKVM_USB_PORT" =~ ^[0-9]+-[0-9]+(\.[0-9]+)*$ ]] || die "That is not a USB port."
    local chosen; chosen="$(printf '%s\n' "$lines" | awk -v p="$DECKVM_USB_PORT" '$1==p {print; exit}')"
    [[ -n "$chosen" ]] || die "That device is no longer plugged in. Plug it in and choose it again."
    read -r PORT DEV_ID DEV_NAME <<<"$chosen"
  elif [[ "$count" -eq 0 ]]; then
    if [[ "$mode" == xbox ]]; then
      die "No Xbox controller found. Plug it in with a USB DATA cable (some charge-only cables carry no data), then try again."
    fi
    die "No external USB device found. Plug it in and try again."
  elif [[ "$count" -eq 1 ]]; then
    read -r PORT DEV_ID DEV_NAME <<<"$lines"
  else
    say "  Several devices found:"
    printf '%s\n' "$lines" | nl -w3 -s') ' | sed 's/^/   /'
    ask "  Which number?" ""
    read -r PORT DEV_ID DEV_NAME <<<"$(printf '%s\n' "$lines" | sed -n "${REPLY}p")"
    [[ -n "${PORT:-}" ]] || die "That is not one of the numbers shown."
  fi
  ok "Using: $DEV_NAME ($DEV_ID) on USB port $PORT"
}

# ---------------------------------------------------------- background jobs ----
bg_start() { # bg_start NAME command...   (output goes to logs/NAME.log)
  local name="$1"; shift
  # A job started from the DeckVM window runs in a pseudo-terminal that is closed when the job ends, and that sends
  # a hang-up to everything still attached to it. setsid detaches the helper so it survives. (Helpers that start
  # with sudo stay attached: sudo's password ticket belongs to the terminal.)
  if [[ "$1" == sudo ]]; then nohup "$@" >>"$LOGS/$name.log" 2>&1 </dev/null &
  else setsid nohup "$@" >>"$LOGS/$name.log" 2>&1 </dev/null &
  fi
  echo "$name:$!" >> "$PIDFILE"
  dbg "started background job $name (pid $!)"
}

# Keeps the Deck awake while Windows runs: waits (up to 2 minutes) for the Windows screen port to open, then holds until it closes.
SLEEP_HOLD='n=0; until (exec 3<>/dev/tcp/127.0.0.1/8006) 2>/dev/null; do n=$((n+1)); [ "$n" -gt 60 ] && exit 0; sleep 2; done; while (exec 3<>/dev/tcp/127.0.0.1/8006) 2>/dev/null; do sleep 5; done  # NerdZapDeckVM-hold'
WATCH_RE=' _(watch(_usb|_kernel|dog)|redir)( .*)?$'   # DeckVM's own helper processes, whatever the script file is called
bg_stop_all() {
  # Administrator-mode helpers (USB sessions) can only be stopped with sudo; a plain Windows session never starts any.
  local rootjobs=0
  [[ "${ACTIVE_ENGINE:-}" == root || "$BASE_ENGINE" == root ]] && rootjobs=1
  if [[ -f "$PIDFILE" ]]; then
    while IFS=: read -r name pid; do
      [[ -n "${pid:-}" ]] || continue
      if ! kill "$pid" 2>/dev/null; then
        [[ $rootjobs == 1 ]] && sudo -n kill "$pid" 2>/dev/null
      fi
      dbg "stopped background job $name (pid $pid)"
    done < "$PIDFILE"
    rm -f "$PIDFILE"
  fi
  pkill -f "who=NerdZapDeckVM" 2>/dev/null
  pkill -f "NerdZapDeckVM-hold" 2>/dev/null
  pkill -f "$WATCH_RE" 2>/dev/null
  if [[ $rootjobs == 1 ]]; then
    sudo -n pkill -f "$RELAY" 2>/dev/null
    sudo -n pkill -f "$USBCAP" 2>/dev/null
    sudo -n pkill -f "$WATCH_RE" 2>/dev/null
    sudo -n pkill -f "cat /sys/kernel/debug/usb/usbmon" 2>/dev/null
  fi
  return 0
}

# A USB session that fails half way must not leave SteamOS without its controller drivers or helpers running.
usb_rollback() {
  USB_ROLLBACK=""
  trap - INT TERM HUP
  say "  Putting SteamOS back as it was..."
  ACTIVE_ENGINE=root
  bg_stop_all
  pm_r rm -f "$NAME" >/dev/null 2>&1 || true
  guacd_stop
  unblock_host_drivers
  local m restore="${USB_UNLOADED:-}"
  for m in ${restore//,/ }; do runq "${SUDO[@]}" modprobe "$m" || true; done
  save_state HOST_MODS_UNLOADED ""
  fix_ownership
  clear_active
  event "USB_ROLLBACK" "start failed; drivers restored: ${restore:-none}"
}
# A connection the Windows screen closed leaves a TIME-WAIT entry on port 8006 for about a minute. The administrator-mode
# engine cannot bind the port while one exists, so a controller session started soon after a normal Windows was stopped fails.
port_tw() { ss -tan 2>/dev/null | awk '$1 == "TIME-WAIT" && $4 ~ /:8006$/ {f=1} END{exit !f}'; }
wait_tw_clear() {
  port_tw || return 0
  say "  Waiting for the Windows screen port to be released (up to a minute)..."
  event "PORT_WAIT_TW" "engine=$ENGINE"
  local i; for i in $(seq 1 80); do port_tw || return 0; sleep 1; done
  return 1
}
wait_port_free() { # wait_port_free PORT [seconds]
  local i; for i in $(seq 1 "${2:-30}"); do port_busy "$1" || return 0; sleep 1; done
  { echo "--- port $1 still busy ---"; ss -tanp 2>/dev/null | grep ":$1 "; ps -eo pid,etimes,args 2>/dev/null | grep -E 'conmon|pasta|rootlessport|slirp|qemu' | grep -v grep; } >> "$LOGS/commands.log" 2>&1
  return 1
}

# QEMU monitor: send commands, print replies. Runs python inside the container.
MONITOR_PY='
import socket, sys, re
cmds = sys.argv[1:]
with socket.socket(socket.AF_UNIX) as s:
    s.settimeout(3)
    s.connect("'"$MONSOCK"'")
    def receive():
        out = b""
        while not out.endswith(b"(qemu) "):
            try:
                chunk = s.recv(4096)
            except socket.timeout:
                break
            if not chunk:
                break
            out += chunk
        return out.decode(errors="replace")
    receive()
    for command in cmds:
        s.sendall((command + "\n").encode())
        raw = receive()
        body = raw.split("\n", 1)[1] if "\n" in raw else raw
        body = re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", body).replace("\r", "").replace("(qemu) ", "").strip()
        print("== " + command)
        print(body if body else "  (ok)")
'
qmon() { pm exec -i "$NAME" python3 - "$@" <<<"$MONITOR_PY" 2>&1; }


# ---- The administrator-mode session helper --------------------------------------------------------------
# During a USB session the watchdog already runs as root (started once, after the password was given). It also answers
# a few fixed requests, so Reconnect and Stop do not ask for the password again. A request is an empty file named
# after the job in $REQDIR; the helper only ever looks at the file's NAME, never its contents. The answer ("request
# <job> done") goes to the watchdog log, which is always owned by the user.
wd_alive() { pgrep -f " _watchdog\$" >/dev/null 2>&1; }
wd_request() { # wd_request JOB [seconds]  ->  0 done, 1 no answer in time, 2 no helper running
  local verb="$1" tmo="${2:-60}" l0 n0 n i
  wd_alive || return 2
  mkdir -p "$REQDIR"
  l0="$(wc -l < "$LOGS/watchdog.log" 2>/dev/null)"; l0="${l0:-0}"
  n0="$(grep -c " request $verb done" "$LOGS/watchdog.log" 2>/dev/null)"; n0="${n0:-0}"
  : > "$REQDIR/$verb"
  for ((i = 0; i < tmo * 2; i++)); do
    n="$(grep -c " request $verb done" "$LOGS/watchdog.log" 2>/dev/null)"; n="${n:-0}"
    if (( n > n0 )); then
      tail -n +$((l0 + 1)) "$LOGS/watchdog.log" 2>/dev/null | grep -v '^ROOTINFO|' | sed 's/^/  /'
      return 0
    fi
    # The helper took the request (the request file is gone) and has ended since: it did its job. The stop helper exits
    # when it is done, and must never leave the caller waiting for a log line that did not get written.
    if (( i >= 4 )) && [[ ! -e "$REQDIR/$verb" ]] && ! wd_alive; then
      tail -n +$((l0 + 1)) "$LOGS/watchdog.log" 2>/dev/null | grep -v '^ROOTINFO|' | sed 's/^/  /'
      return 0
    fi
    sleep 0.5
  done
  rm -f "$REQDIR/$verb"
  return 1
}

# A USB bus reset from the host side (what the "usbreset" tool does). Only while nothing is holding the device.
usb_host_reset() {
  local bn dn
  bn="$(cat "$SYSFS/$1/busnum" 2>/dev/null)"; dn="$(cat "$SYSFS/$1/devnum" 2>/dev/null)"
  [[ -n "$bn" && -n "$dn" ]] || return 1
  python3 -I -c 'import fcntl, os, sys
fd = os.open(sys.argv[1], os.O_WRONLY)
fcntl.ioctl(fd, 0x5514)   # USBDEVFS_RESET
os.close(fd)' "$(printf '/dev/bus/usb/%03d/%03d' "$bn" "$dn")" 2>/dev/null
}

# Where the passed-through devices are: the first one (PORT, id deckvm-usb) and any extra ones (EXTRA_PORTS, ids deckvm-usb2...)
session_ports() { # prints "port id" lines
  local i=1 p
  echo "${PORT:-} $USBDEV_ID"
  for p in ${EXTRA_PORTS:-}; do i=$((i + 1)); echo "$p ${USBDEV_ID}$i"; done
}

# Take every passed-through device out of Windows, reset it on the host, and add it back. Needs root (the QEMU monitor
# lives in the administrator-mode container).
reattach_now() {
  local port id bus hport any=0
  while read -r port id; do
    [[ -n "$port" ]] || continue
    if [[ ! -r "$SYSFS/$port/idVendor" ]]; then echo "The device on port $port is not plugged in. Plug it in, wait a second, then try again."; continue; fi
    any=1; bus="${port%%-*}"; hport="${port#*-}"
    echo "Taking the device on port $port out of Windows..."
    if [[ "${REDIR_ON:-0}" == 1 ]]; then
      redir_kill "$id"
      sleep 2
      if usb_host_reset "$port"; then echo "Reset the device on the Deck's side."; else echo "(Could not reset the device on the Deck's side; carrying on.)"; fi
      echo "The USB redirector gives it back to Windows by itself in a few seconds."
      event "REATTACH" "port=$port redirect"
      continue
    fi
    qmon "device_del $id" | sed 's/^/    /'
    sleep 2
    if usb_host_reset "$port"; then echo "Reset the device on the Deck's side."; else echo "(Could not reset the device on the Deck's side; carrying on.)"; fi
    sleep 2
    echo "Giving it back to Windows..."
    qmon "device_add usb-host,hostbus=$bus,hostport=$hport,id=$id" | sed 's/^/    /'
    event "REATTACH" "port=$port"
  done < <(session_ports)
  [[ $any == 1 ]]
}

# The administrator-mode half of Stop: shut Windows down, give the USB devices back to SteamOS, hand files back to the
# user and end the other administrator-mode helpers of this session. Runs as root, inside the watchdog.
root_stop_part() {
  ACTIVE_ENGINE=root; ENGINE=root
  local s; s="$(engine_vm_state root)"
  if [[ "$s" == running ]]; then
    echo "Asking Windows to shut down (up to 2 minutes)..."
    runq pm_r stop -t 120 "$NAME"
  fi
  [[ "$s" == running || "$s" == stopped ]] && pm_r rm -f "$NAME" >/dev/null 2>&1
  guacd_stop
  unblock_host_drivers
  local m restore="${HOST_MODS_UNLOADED:-}"
  for m in ${restore//,/ }; do
    runq "${SUDO[@]}" modprobe "$m" && event "HOST_DRIVER_RESTORED" "$m" || echo "Could not reload $m. A restart of the Deck fixes this."
  done
  fix_ownership
  pkill -f "who=NerdZapDeckVM" 2>/dev/null
  pkill -f "$RELAY" 2>/dev/null
  pkill -f "$USBCAP" 2>/dev/null
  pkill -f " _watch_kernel\$" 2>/dev/null
  pkill -f " _redir " 2>/dev/null
  return 0
}

# Administrator-mode details for the report (printed with a marker so the report can pick them out of the log)
root_info_part() {
  ENGINE=root
  echo "ROOTINFO|BEGIN"
  { pm info --format '{{.Host.OCIRuntime.Name}} cgroups={{.Host.CgroupsVersion}} driver={{.Store.GraphDriverName}} root={{.Store.GraphRoot}}'; pm images; rep_container_one; } 2>&1 | sed 's/^/ROOTINFO|/'
  echo "ROOTINFO|END"
}

# Hidden helper: logs every change in the passed-through device, with the host driver that owns it.
cmd__watch_usb() {
  local last="" now line
  echo "$(ts) usb watcher started (every 1s; logs changes only)"
  while true; do
    now=""
    while read -r line; do
      [[ -n "$line" ]] || continue
      now+="${line%% *} $(echo "$line" | cut -d' ' -f2-) [drv=$(host_driver_of "${line%% *}")];"
    done < <(list_usb all | sort)
    now+=" mods=[$(lsmod | awk '$1=="xbox_gip"||$1=="xpad"{printf "%s ", $1}')]"
    if [[ "$now" != "$last" ]]; then
      if [[ "$now" == " mods="* ]]; then echo "$(ts) USB CHANGE: <no external USB device present>${now}"; else echo "$(ts) USB CHANGE: ${now}"; fi
      last="$now"
    fi
    sleep 1
  done
}
cmd__watch_kernel() { exec "${SUDO[@]}" journalctl -k -f -o short-iso --no-pager 2>&1; }

# ---- USB redirection (default since live57) ---------------------------------------------------------------------
# Until live56 the controller was handed to QEMU as a "usb-host" device. When the controller restarted itself (every
# firmware update does), QEMU sometimes aborted on an internal check (usb_handle_packet / usb_host_ep_update), which
# killed Windows in the middle of an update. Redirection is the route made for this: a small program on the Deck's side
# ("usbredirect") reads the real device and talks to QEMU over a local socket. When the device goes away, that
# connection simply closes and Windows sees an ordinary unplug; when it comes back, a new connection is opened and
# Windows sees an ordinary plug-in. QEMU never has to carry a device through a restart.
# The program lives in a copy of the VM image with one extra package (built once, a minute). DECKVM_USB_MODE=host (or
# USB_MODE=host in config.env) switches back to the old way.
REDIR_PORT_BASE=47100          # loopback TCP ports inside the Windows container: BASE for the first device, +1 for each extra one
usb_mode() { local m="${DECKVM_USB_MODE:-${USB_MODE:-redir}}"; [[ "$m" == host ]] && echo host || echo redir; }
redir_args() { # redir_args INDEX ID -> the QEMU arguments for one redirected device
  echo "-chardev socket,id=$2-ch,host=127.0.0.1,port=$((REDIR_PORT_BASE + $1)),server=on,wait=off -device usb-redir,chardev=$2-ch,id=$2"
}
ensure_redir_image() { # builds (once) a copy of the VM image that has usbredirect in it and checks it; sets RUN_IMAGE. Needs the administrator engine.
  local tag id dir
  ENGINE=root
  ensure_image
  id="$(pm_r image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null | head -n1)"; id="${id#sha256:}"; id="${id:0:12}"
  [[ -n "$id" ]] || { event "REDIR_IMAGE_FAIL" "base image not found"; return 1; }
  tag="localhost/deckvm-redir:$id"
  if ! pm_r image exists "$tag" 2>/dev/null; then
    say "  Preparing the USB redirector (one time, about a minute)..."
    dir="$RUNTIME/redir-build"; rm -rf "$dir"; mkdir -p "$dir"
    printf 'FROM %s\nRUN apt-get update && apt-get install -y --no-install-recommends usbredirect && rm -rf /var/lib/apt/lists/*\n' "$IMAGE" > "$dir/Containerfile"
    if ! runq pm_r build --pull=never -t "$tag" -f "$dir/Containerfile" "$dir"; then
      event "REDIR_IMAGE_FAIL" "build failed (see commands.log)"; rm -rf "$dir"; return 1
    fi
    rm -rf "$dir"
  fi
  if ! runq pm_r run --rm --entrypoint /usr/bin/usbredirect "$tag" --help; then event "REDIR_IMAGE_FAIL" "usbredirect does not run"; return 1; fi
  # read the whole list first: "qemu ... | grep -q" can die of SIGPIPE under pipefail and wrongly report "no usb-redir"
  local devlist; devlist="$(pm_r run --rm --entrypoint qemu-system-x86_64 "$tag" -device help 2>/dev/null)"
  if ! grep -q '"usb-redir"' <<<"$devlist"; then event "REDIR_IMAGE_FAIL" "this QEMU has no usb-redir (device list had $(wc -l <<<"$devlist") lines)"; return 1; fi
  RUN_IMAGE="$tag"
  event "REDIR_IMAGE_OK" "$tag"
  return 0
}
redir_kill() { # redir_kill ID: end the redirect of one device (the helper starts a new one when the device is ready)
  pm_r exec "$NAME" sh -c "p=\$(cat /tmp/deckvm-redir-$1.pid 2>/dev/null); [ -n \"\$p\" ] && { kill \$p 2>/dev/null; sleep 2; kill -9 \$p 2>/dev/null; }; true" >/dev/null 2>&1
}
cmd__redir() { # _redir PORT ID TCPPORT: keeps one USB device handed to Windows through usbredirect (administrator mode)
  ENGINE=root
  load_conf; load_state
  local rport="$1" rid="$2" tcp="$3" settle="${WD_SETTLE:-3}"
  local dn="" seen="" stable=0 chk=0 away=0 fast=0 ready=0 bus pid rc t0 now cur
  echo "$(ts) redirector started: port=$rport id=$rid tcp=$tcp settle=${settle}s"
  while true; do
    chk=$((chk + 1))
    if (( chk % 5 == 0 )); then
      case "$(engine_vm_state root)" in running) away=0;; *) away=$((away + 1));; esac
      if (( away >= 3 )); then echo "$(ts) Windows is not running any more: redirector finished"; exit 0; fi
    fi
    if [[ -r "$SYSFS/$rport/idVendor" ]]; then
      dn="$(cat "$SYSFS/$rport/devnum" 2>/dev/null)"
      if [[ "$dn" == "$seen" ]]; then stable=$((stable + 1)); else seen="$dn"; stable=0; echo "$(ts) device present on $rport (USB address $dn)"; fi
      if (( stable >= settle )); then
        # QEMU must be listening before the device is opened (opening it makes the controller restart its USB session)
        if [[ $ready == 0 ]]; then
          if pm_r exec "$NAME" test -S "$MONSOCK" >/dev/null 2>&1; then ready=1; else sleep 2; continue; fi
        fi
        bus="$(cat "$SYSFS/$rport/busnum" 2>/dev/null)"
        echo "$(ts) handing USB address $bus-$dn to Windows"
        t0=$(date +%s)
        pm_r exec "$NAME" sh -c "echo \$\$ > /tmp/deckvm-redir-$rid.pid; exec /usr/bin/usbredirect --device $bus-$dn --to 127.0.0.1:$tcp" >> "$LOGS/redir-$rid.out" 2>&1 &
        pid=$!
        local inner=0
        while kill -0 "$pid" 2>/dev/null; do
          sleep 0.5
          inner=$((inner + 1))
          if (( inner % 10 == 0 )); then
            case "$(engine_vm_state root)" in running) away=0;; *) away=$((away + 1));; esac
            if (( away >= 3 )); then echo "$(ts) Windows is not running any more: ending the redirect"; redir_kill "$rid"; wait "$pid" 2>/dev/null; echo "$(ts) redirector finished"; exit 0; fi
          fi
          cur=""; [[ -r "$SYSFS/$rport/idVendor" ]] && cur="$(cat "$SYSFS/$rport/devnum" 2>/dev/null)"
          if [[ "$cur" != "$dn" ]]; then
            if [[ -n "$cur" ]]; then echo "$(ts) the device came back as USB address $cur: ending the old redirect, Windows sees an unplug"
            else echo "$(ts) the device dropped off the USB bus: ending its redirect, Windows sees an unplug"; fi
            redir_kill "$rid"
            break
          fi
        done
        wait "$pid" 2>/dev/null; rc=$?
        now=$(date +%s)
        echo "$(ts) redirect ended after $((now - t0))s (exit $rc)"
        if (( now - t0 < 4 )); then fast=$((fast + 1)); else fast=0; fi
        if (( fast >= 3 )); then
          echo "$(ts) the redirect keeps ending at once (${fast}x): waiting a little before trying again. Output so far is in redir-$rid.out"
          [[ $fast -eq 3 ]] && event "REDIR_FAILING" "id=$rid"
          sleep $(( fast > 8 ? 15 : 5 ))
        fi
        seen=""; stable=0; sleep 1
        continue
      fi
    else
      [[ -n "$seen" ]] && echo "$(ts) device is gone from $rport"
      seen=""; stable=0
    fi
    sleep 1
  done
}

# Hidden helper: the re-attach watchdog.
# 1) During a firmware update the controller resets and comes back. QEMU normally re-claims it within a second or two. If the
#    device is back on the host but nobody owns it (driver "none") for WD_GRACE seconds, detach and re-attach it inside QEMU,
#    which is exactly what physically replugging does.
# 2) If the device stays unplugged for WD_GONE seconds (longer than a normal reset), take it out of the VM straight away. This
#    matters when a DIFFERENT controller is plugged into the same port: left to itself, QEMU grabs the new device while still
#    holding the old one's state and crashes ("usb_host_ep_update: Assertion ... failed", seen in testing). Once the new
#    device has settled it is added to the VM fresh.
cmd__watchdog() { # _watchdog [PORT ID]: with no arguments it watches the first device and answers the session's requests
  load_conf; load_state
  local wport="${1:-$PORT}" wid="${2:-$USBDEV_ID}" primary=1
  [[ -n "${1:-}" && "$1" != "${PORT:-}" ]] && primary=0
  # Fresh-attach mode (default): every time the device drops off the bus or comes back as a new USB device, take it out of
  # the VM at once and add it back fresh after a short settle. QEMU 11 can abort ("usb_host_ep_update: Assertion alt <
  # num_altsetting failed") when it re-grabs a device by itself after the device re-enumerated with different USB descriptors,
  # for example when a controller is flashed back to older firmware. The relay holds back the "add" event for 3 s so this
  # watchdog has already taken the old device out of the VM when QEMU's USB library hears about the new one (the library
  # must still hear about it, or device_add cannot find the device). DECKVM_FRESH_ATTACH=0 restores the old behaviour.
  local fresh="${DECKVM_FRESH_ATTACH:-1}" dn dn_last=""
  local grace="${WD_GRACE:-8}" gone_after="${WD_GONE:-4}" settle="${WD_SETTLE:-3}"
  if [[ $fresh == 1 ]]; then grace="${WD_GRACE:-8}"; gone_after="${WD_GONE:-0}"; settle="${WD_SETTLE:-4}"; fi
  local since=0 gone_since=0 removed=0 last_try=0 tries=0 drv now bus hport chk=0 away=0
  bus="${wport%%-*}"; hport="${wport#*-}"
  echo "$(ts) watchdog started: port=$wport grace=${grace}s fresh_attach=$fresh usb_redirect=${REDIR_ON:-0}"
  while true; do
    now=$(date +%s)
    # every few seconds: is Windows still there? If not, this helper has nothing left to do.
    chk=$((chk + 1))
    if (( chk % 5 == 0 )); then
      case "$(engine_vm_state root)" in running) away=0;; *) away=$((away + 1));; esac
      if (( away >= 3 )); then
        echo "$(ts) Windows is not running any more: watchdog finished"
        if [[ $primary == 1 ]]; then
          # Give SteamOS its controller drivers back now, so the user does not have to press Stop (and type the password again).
          echo "$(ts) giving the devices and drivers back to SteamOS"
          root_stop_part 2>&1 | sed 's/^/    /'
          : > "$RUNTIME/restored"; chown "${SUDO_USER:-$(stat -c %U "$BASE" 2>/dev/null)}" "$RUNTIME/restored" 2>/dev/null
          echo "$(ts) done"
        fi
        exit 0
      fi
    fi
    if [[ $primary == 1 && -d "$REQDIR" ]]; then
      if [[ -e "$REQDIR/reattach" ]]; then
        rm -f "$REQDIR/reattach"
        echo "$(ts) request reattach: reconnecting the device"
        reattach_now | sed 's/^/    /'
        echo "$(ts) request reattach done"
        since=0; tries=0; removed=0; last_try=$(date +%s)
      fi
      if [[ -e "$REQDIR/rootinfo" ]]; then
        rm -f "$REQDIR/rootinfo"
        root_info_part
        echo "$(ts) request rootinfo done"
      fi
      if [[ -e "$REQDIR/stop" ]]; then
        rm -f "$REQDIR/stop"
        echo "$(ts) request stop: stopping Windows and giving the devices back"
        root_stop_part 2>&1 | sed 's/^/    /'
        echo "$(ts) request stop done"
        exit 0
      fi
    fi
    if [[ "${REDIR_ON:-0}" == 1 ]]; then sleep 1; continue; fi   # USB redirect mode: cmd__redir looks after the device; this helper only answers requests and cleans up
    if [[ -r "$SYSFS/$wport/idVendor" ]]; then
      gone_since=0
      if [[ $fresh == 1 ]]; then
        dn="$(cat "$SYSFS/$wport/devnum" 2>/dev/null)"
        if [[ -n "$dn_last" && -n "$dn" && "$dn" != "$dn_last" && $removed -eq 0 ]]; then
          echo "$(ts) the device came back as a new USB device (address $dn_last to $dn): taking the old one out of the VM so it is added back fresh"
          qmon "device_del $wid" | sed 's/^/    /'
          removed=1; since=0
        fi
        [[ -n "$dn" ]] && dn_last="$dn"
      fi
      drv="$(host_driver_of "$wport")"
      if [[ "$drv" == *usbfs* ]]; then
        if [[ $since -ne 0 ]]; then echo "$(ts) device is owned by the VM again"; fi
        since=0; tries=0; removed=0
      elif [[ "$drv" == none ]]; then
        [[ $since -eq 0 ]] && since=$now
        if [[ $removed -eq 1 ]]; then
          if (( now - since >= settle )); then
            echo "$(ts) a device is back after being unplugged: adding it to the VM"
            qmon "device_add usb-host,hostbus=$bus,hostport=$hport,id=$wid" | sed 's/^/    /'
            removed=0; since=0; last_try=$now
          fi
        elif (( now - since >= grace )) && (( now - last_try >= 15 )) && (( tries < 8 )); then
          tries=$((tries+1)); last_try=$now
          echo "$(ts) device back on the host for $((now - since))s but not attached to the VM: re-attaching (try $tries)"
          qmon "device_del $wid" "device_add usb-host,hostbus=$bus,hostport=$hport,id=$wid" | sed 's/^/    /'
        fi
      else
        if [[ $since -ne 0 ]]; then since=0; fi
      fi
    else
      since=0
      [[ $gone_since -eq 0 ]] && gone_since=$now
      if [[ $removed -eq 0 ]] && (( now - gone_since >= gone_after )); then
        if [[ $fresh == 1 ]]; then echo "$(ts) the device dropped off the USB bus: taking it out of the VM so it is added back fresh when it returns"
        else echo "$(ts) device unplugged for ${gone_after}s: taking it out of the VM until something is plugged in again"; fi
        qmon "device_del $wid" | sed 's/^/    /'
        removed=1
      fi
    fi
    sleep 1
  done
}

# ------------------------------------------------- engines, ownership, deleting ----
# Rootless Podman needs these. All of them are normally present on a Steam Deck; if not, we fall back to
# administrator mode for everything (which asks for the password).
rootless_prereqs() { # sets ROOTLESS_WHY when it returns 1
  local me uid; me="$(id -un)"; uid="$(id -u)"; ROOTLESS_WHY=""
  command -v podman >/dev/null || { ROOTLESS_WHY="podman is missing"; return 1; }
  { command -v newuidmap >/dev/null && command -v newgidmap >/dev/null; } || { ROOTLESS_WHY="newuidmap/newgidmap are missing"; return 1; }
  { grep -Eq "^($me|$uid):" /etc/subuid 2>/dev/null && grep -Eq "^($me|$uid):" /etc/subgid 2>/dev/null; } || { ROOTLESS_WHY="no subuid/subgid range for $me"; return 1; }
  { command -v pasta >/dev/null || command -v slirp4netns >/dev/null; } || { ROOTLESS_WHY="no rootless network helper (pasta or slirp4netns)"; return 1; }
  [[ -r /dev/kvm && -w /dev/kvm ]] || { ROOTLESS_WHY="/dev/kvm is not usable by your user"; return 1; }
  mkdir -p "$PODROOT_U" "$PODRUN_U" 2>/dev/null; chmod 700 "$PODRUN_U" 2>/dev/null
  pm_u info >/dev/null 2>&1 || { ROOTLESS_WHY="podman could not start in normal user mode"; return 1; }
  return 0
}

# Files a rootful (USB) session creates are owned by root and would block the next normal-user start.
# Only the folders this tool writes through the container are touched (never the rootless image store, whose
# files legitimately belong to sub-user ids).
owned_dirs() { local d; for d in "$STORAGE" "$OEM" "$SHARED" "$LOGS" "$RUNTIME"; do [[ -e "$d" ]] && printf '%s\n' "$d"; done; }
foreign_files() {
  local me; me="${SUDO_USER:-$(id -un)}"
  mapfile -t _od < <(owned_dirs)
  [[ ${#_od[@]} -gt 0 ]] && find "${_od[@]}" -not -user "$me" -print -quit 2>/dev/null
  [[ -d "$BASE" ]] && find "$BASE" -maxdepth 1 -type f -not -user "$me" -print -quit 2>/dev/null
  return 0
}
fix_ownership() { # needs root (only called when sudo is already available)
  local me grp; me="${SUDO_USER:-$(id -un)}"; grp="$(id -gn "$me" 2>/dev/null || id -gn)"
  mapfile -t _od < <(owned_dirs)
  [[ ${#_od[@]} -gt 0 ]] && "${SUDO[@]}" chown -R "$me:$grp" "${_od[@]}" 2>/dev/null
  [[ -d "$BASE" ]] && "${SUDO[@]}" find "$BASE" -maxdepth 1 -type f -exec chown "$me:$grp" {} + 2>/dev/null
  dbg "ownership handed back to $me"
  return 0
}
ensure_user_owned() {
  [[ $EUID -eq 0 ]] && return 0
  [[ -n "$(foreign_files)" ]] || return 0
  say "  DeckVM needs your password once to tidy up after a controller session."
  need_sudo "to fix file ownership"
  fix_ownership
}

# Delete folders that may contain root-owned files (USB sessions) or sub-user-id files (rootless store).
rm_tree() {
  local p
  for p in "$@"; do
    [[ -e "$p" || -L "$p" ]] || continue
    rm -rf "$p" 2>/dev/null
    [[ -e "$p" ]] && command -v podman >/dev/null && { pm_u unshare rm -rf "$p" 2>/dev/null || podman unshare rm -rf "$p" 2>/dev/null; }
    if [[ -e "$p" ]]; then
      need_sudo "to delete files owned by administrator mode"
      "${SUDO[@]}" rm -rf "$p"
    fi
  done
  return 0
}
dir_size() { du -sch "$@" 2>/dev/null | tail -n 1 | cut -f1; }

# Is administrator-mode state left behind that a Stop must clean up?
root_traces() {
  [[ "${ACTIVE_ENGINE:-}" == root || "$BASE_ENGINE" == root || -n "${HOST_MODS_UNLOADED:-}" || -e "$MODCONF_ETC" || -e "$MODCONF_RUN" ]]
}

# ---------------------------------------------------------------- preflight ----
preflight() { # preflight  -> sets FAILS; prints only what matters
  FAILS=0; WARNS=0
  local model free ram_gb
  model="$(cat /sys/class/dmi/id/product_name 2>/dev/null || echo unknown)"
  case "$model" in
    Jupiter) ok "Steam Deck LCD";;
    Galileo) ok "Steam Deck OLED";;
    *) warn "This is '$model', not a Steam Deck. It may still work, but it is only tested on a Deck.";;
  esac
  ram_gb=$(awk '/MemTotal/ {printf "%d", $2/1024/1024}' /proc/meminfo)
  [[ "${ram_gb:-0}" -ge 12 ]] && ok "Memory: ${ram_gb} GB" || warn "Memory: ${ram_gb} GB. Windows may be slow; use a smaller VM memory setting."
  free=$(free_gb "$HOME")
  if   [[ "${free:-0}" -ge 50 ]]; then ok "Free space in your home folder: ${free} GB"
  elif [[ "${free:-0}" -ge 40 ]]; then warn "Free space: ${free} GB. Tight; 50 GB or more is safer."
  else fail "Free space: ${free:-?} GB. Windows needs about 40 GB. Free some space or use an SD card install."; fi
  [[ -e /dev/kvm ]] && ok "Hardware virtualisation (KVM) is available" || fail "KVM is not available, so Windows would be far too slow."
  if command -v podman >/dev/null; then ok "Podman: $(podman --version | awk '{print $NF}')"; else fail "Podman is not installed on this system."; fi
  if command -v python3 >/dev/null && python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3,10) else 1)'; then ok "Python $(python3 --version | awk '{print $2}')"; else fail "Python 3.10 or newer is needed."; fi
  if [[ "${DECKVM_ROOTFUL:-0}" != 1 ]] && rootless_prereqs; then
    BASE_ENGINE=user; ENGINE=user; save_conf ROOTLESS 1; ROOTLESS=1
    ok "Windows runs in normal user mode: no password needed"
  else
    BASE_ENGINE=root; ENGINE=root; save_conf ROOTLESS 0; ROOTLESS=0
    warn "Normal user mode is not available (${ROOTLESS_WHY:-switched off}). Using administrator mode, which asks for your password."
    if need_sudo_quiet; then
      ok "Administrator access (sudo) works"
      if command -v podman >/dev/null && ! pm info >/dev/null 2>&1; then fail "Podman could not start in administrator mode. Details are in the report."; fi
    else
      fail "No administrator access. Set a password (run 'passwd' in a terminal) and try again."
    fi
  fi
  command -v systemd-inhibit >/dev/null || warn "systemd-inhibit missing: the Deck might sleep during long jobs."
  dbg "preflight finished: fails=$FAILS warns=$WARNS model=$model"
  [[ $FAILS -eq 0 ]]
}

# --------------------------------------------------------------- VM plumbing ----
write_touchkb_bat() { # a double-click helper for a Windows that was set up before the touch keyboard setting was part of the install
  mkdir -p "$SHARED"
  {
    printf '%s\n' '@echo off' 'rem NerdZap DeckVM: always show the touch keyboard when a text box is tapped.' \
      'reg add "HKCU\Software\Microsoft\TabletTip\1.7" /v TouchKeyboardTapInvoke /t REG_DWORD /d 2 /f' \
      'reg add "HKCU\Software\Microsoft\TabletTip\1.7" /v EnableDesktopModeAutoInvoke /t REG_DWORD /d 1 /f' \
      'reg add "HKCU\Software\Microsoft\TabletTip\1.7" /v TipbandDesiredVisibility /t REG_DWORD /d 1 /f' \
      'echo.' 'echo Done. Tap a text box to see the touch keyboard.' 'pause'
  } | sed 's/$/\r/' > "$SHARED/Turn on touch keyboard.bat"
}

write_oem() {
  mkdir -p "$OEM" "$SHARED"
  { cat <<'BAT'
@echo off
rem NerdZap DeckVM: runs once at the end of the automatic Windows install.
set LOGF=C:\OEM\nerdzap-install.log
echo [%date% %time%] OEM install.bat started > "%LOGF%"
ver >> "%LOGF%"
rem Touch keyboard: Windows should open it whenever a text box is tapped, even though it believes a keyboard is attached
reg load HKU\DeckVMDef "C:\Users\Default\NTUSER.DAT" >nul 2>&1
for %%H in (HKCU HKU\DeckVMDef) do (
  reg add "%%H\Software\Microsoft\TabletTip\1.7" /v TouchKeyboardTapInvoke /t REG_DWORD /d 2 /f >nul 2>&1
  reg add "%%H\Software\Microsoft\TabletTip\1.7" /v EnableDesktopModeAutoInvoke /t REG_DWORD /d 1 /f >nul 2>&1
  reg add "%%H\Software\Microsoft\TabletTip\1.7" /v TipbandDesiredVisibility /t REG_DWORD /d 1 /f >nul 2>&1
)
reg unload HKU\DeckVMDef >nul 2>&1
echo [%date% %time%] touch keyboard setting written >> "%LOGF%"
rem One-click shortcut straight to the Xbox Accessories page of the Microsoft Store
set SC=C:\Users\Public\Desktop\Install Xbox Accessories.url
echo [InternetShortcut]> "%SC%"
echo URL=ms-windows-store://pdp/?ProductId=9NBLGGH30XJ3>> "%SC%"
BAT
    cat <<'BAT'
echo [%date% %time%] OEM install.bat finished >> "%LOGF%"
if not exist Z:\ net use Z: \\host.lan\Data /persistent:no >nul 2>&1
if exist Z:\ copy /Y "%LOGF%" Z:\nerdzap-install.log >nul
BAT
  } | sed 's/$/\r/' > "$OEM/install.bat"
  # The same shortcut in the Shared folder, so it is always available (also on a Windows installed earlier)
  printf '[InternetShortcut]\r\nURL=ms-windows-store://pdp/?ProductId=9NBLGGH30XJ3\r\n' > "$SHARED/Install Xbox Accessories.url"
  rm -f "$SHARED/Try installing Xbox Accessories (winget).bat"   # older builds made this file
  write_touchkb_bat
  if [[ "${DECKVM_DEV:-0}" == 1 && "${RESEARCH:-0}" == 1 ]]; then
    # Developer builds only (DECKVM_DEV=1). Public builds never write this helper, and remove an older copy below.
    cat > "$SHARED/Collect research files.bat" <<'BAT'
@echo off
rem NerdZap research helper: copies what the Xbox Accessories app stored, plus recent DNS names, to Z:\research
set OUT=Z:\research
mkdir "%OUT%" 2>nul
echo Collecting... this can take a minute.
ipconfig /displaydns > "%OUT%\dns-cache.txt"
robocopy "%LOCALAPPDATA%\Packages" "%OUT%\packages" /E /R:0 /W:0 /NFL /NDL /NJH /NJS /XD "Microsoft.WindowsStore_*" "Microsoft.Windows.*" "MicrosoftWindows.*" "Microsoft.AAD*" "Microsoft.Win32*" "windows.immersivecontrolpanel*" >nul
powershell -NoProfile -Command "Get-ChildItem -Path $env:LOCALAPPDATA,$env:ProgramData,$env:TEMP,$env:WINDIR\Temp -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.Length -gt 51200 -and $_.LastWriteTime -gt (Get-Date).AddHours(-3) } | Select-Object FullName,Length,LastWriteTime | Out-File -Width 400 '%OUT%\recent-files.txt'"
powershell -NoProfile -Command "Get-AppxPackage | Where-Object { $_.Name -match 'Xbox|Gaming|GameInput' } | Select-Object Name,Version,InstallLocation,PackageFullName | Format-List | Out-File -Width 400 '%OUT%\appx.txt'"
powershell -NoProfile -Command "$o='%OUT%\app-files.txt'; '' | Out-File $o; foreach($p in (Get-AppxPackage | Where-Object { $_.Name -match 'XboxDevices|XboxAccessories|GamingServices' })){ ('== '+$p.PackageFullName+'  '+$p.InstallLocation) | Out-File -Append $o; Get-ChildItem -Path $p.InstallLocation -Recurse -File -Force -ErrorAction SilentlyContinue | ForEach-Object { $h=''; if($_.Length -gt 2048 -and $_.Length -lt 20MB){ $h=(Get-FileHash $_.FullName -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash }; ($_.FullName.Substring($p.InstallLocation.Length)+'  '+$_.Length+'  '+$h) | Out-File -Append -Width 400 $o } }"
powershell -NoProfile -Command "Get-ChildItem -Path $env:WINDIR\SoftwareDistribution\Download,$env:ProgramData\Microsoft\Windows\DeliveryOptimization,$env:WINDIR\System32\DriverStore\FileRepository -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-6) } | Select-Object FullName,Length,LastWriteTime | Out-File -Width 400 '%OUT%\update-downloads.txt'"
pnputil /enum-devices /connected > "%OUT%\pnp-devices.txt" 2>&1
wevtutil qe System /c:200 /rd:true /f:text /q:"*[System[Provider[@Name='Microsoft-Windows-USB-USBXHCI' or @Name='Microsoft-Windows-Kernel-PnP' or @Name='Microsoft-Windows-DriverFrameworks-UserMode']]]" > "%OUT%\system-events.txt" 2>&1
echo Done. The files are in the Shared folder under "research".
pause
BAT
  else
    rm -f "$SHARED/Collect research files.bat"
  fi
}

extract_helpers() {
  mkdir -p "$BASE"
  cat > "$RELAY" <<'RELAY_PY_EOF'
#!/usr/bin/env python3
"""Relay processed host udev events for one Microsoft USB port into a container.

Adapted from zedxter/xbox-firmware-linux (MIT licence, Copyright (c) 2026 zedxter)
for rootful Podman on SteamOS. The filtering and the setns/netlink approach are
theirs; changes here: the container PID, USB port and vendor ID come from
arguments (no Docker inspect, not Microsoft-only), and every line is timestamped
for the NerdZap log.

Why this exists: when the controller flashes it resets its USB connection and
may re-enumerate with a different product ID. QEMU inside the container does not
see the kernel's hotplug events, so it never re-attaches the device. This script
copies the host's processed udev add/remove events for ONE physical port into the
container's network namespace so libusb inside QEMU notices the device again.
"""
import argparse
import ctypes
import os
import select
import socket
import struct
import subprocess
import sys
import time
from pathlib import Path


def say(message):
    print(time.strftime('%Y-%m-%d %H:%M:%S'), message, flush=True)


def properties(packet):
    if len(packet) < 40 or packet[:8] != b'libudev\0':
        return {}
    offset, length = struct.unpack_from('=II', packet, 16)
    if offset < 40 or offset + length > len(packet):
        return {}
    fields = packet[offset:offset + length].split(b'\0')
    result = {}
    for field in fields:
        if b'=' in field:
            key, value = field.split(b'=', 1)
            if key in result:
                return {}  # Reject ambiguous security-relevant fields.
            result[key] = value
    return result


def allowed(props, devpath, want_vendor):
    try:
        vendor = int(props.get(b'PRODUCT', b'').split(b'/')[0], 16)
    except ValueError:
        return False
    return (vendor == want_vendor and props.get(b'DEVPATH') == devpath
            and props.get(b'SUBSYSTEM') == b'usb'
            and props.get(b'DEVTYPE') == b'usb_device'
            and props.get(b'ACTION') in (b'add', b'remove'))


def root_packet(ancillary, flags):
    if flags & (socket.MSG_TRUNC | socket.MSG_CTRUNC):
        return False
    creds = [struct.unpack('3i', data[:12]) for level, kind, data in ancillary
             if level == socket.SOL_SOCKET and kind == socket.SCM_CREDENTIALS and len(data) >= 12]
    return len(creds) == 1 and creds[0][1] == 0


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--pid', type=int, required=True, help='PID of the running container')
    parser.add_argument('--port', required=True, help='physical USB port, e.g. 3-1 or 1-2.3')
    parser.add_argument('--vendor', default='045e', help='USB vendor ID (hex) of the device on that port')
    parser.add_argument('--hold-add', type=float, default=0.0, metavar='SECONDS',
                        help='forward "add" events this many seconds late, so the watchdog can take the old device out of '
                             'the VM first (QEMU can crash when it re-grabs a device that came back with different USB descriptors)')
    args = parser.parse_args()
    if os.geteuid() != 0:
        raise SystemExit('Run as root')
    path = Path('/sys/bus/usb/devices') / args.port
    want_vendor = int(args.vendor, 16)
    if not (path / 'idVendor').exists() or int((path / 'idVendor').read_text().strip(), 16) != want_vendor:
        raise SystemExit(f'No device with vendor {args.vendor} on port {args.port}. Plug it in first.')
    devpath = str(path.resolve()).removeprefix('/sys').encode()
    say(f'relay: port={args.port} devpath={devpath.decode()} container_pid={args.pid}')
    pidfd = os.pidfd_open(args.pid)  # avoids following a reused PID
    poller = select.poll()
    poller.register(pidfd, select.POLLIN)
    libc = ctypes.CDLL(None, use_errno=True)

    def enter(fd):
        if libc.setns(fd, 0x40000000) != 0:  # CLONE_NEWNET
            raise OSError(ctypes.get_errno(), 'setns failed')

    with socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, 15) as receiver:
        receiver.setsockopt(socket.SOL_SOCKET, socket.SO_PASSCRED, 1)
        receiver.bind((0, 2))
        receiver.settimeout(1)
        host_ns = os.open('/proc/self/ns/net', os.O_RDONLY)
        target_ns = os.open(f'/proc/{args.pid}/ns/net', os.O_RDONLY)
        try:
            enter(target_ns)
            sender = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, 15)
            sender.bind((0, 0))
        finally:
            enter(host_ns)
            os.close(host_ns)
            os.close(target_ns)
        with sender:
            say('READY: forwarding udev events for the selected port. Keep this running during updates.')
            started = time.monotonic()
            seeded = False
            seen = 0
            held = []
            while not poller.poll(0):
                while held and held[0][0] <= time.monotonic():
                    sender.sendto(held.pop(0)[1], (0, 2))
                    seen += 1
                    say(f'FORWARDED add (held) (#{seen})')
                if not seeded and time.monotonic() - started > 15:
                    if path.exists():
                        subprocess.run(['udevadm', 'trigger', '--action=add', str(path)], check=False)
                        say('seeded: sent a synthetic add event for the current device')
                    seeded = True
                try:
                    packet, ancillary, flags, _ = receiver.recvmsg(65536, socket.CMSG_SPACE(12))
                except socket.timeout:
                    continue
                if not root_packet(ancillary, flags):
                    continue
                props = properties(packet)
                if allowed(props, devpath, want_vendor):
                    if props[b'ACTION'] == b'remove' and held:
                        say(f'dropping {len(held)} held add event(s): that device is already gone again')
                        held.clear()
                    if args.hold_add > 0 and props[b'ACTION'] == b'add':
                        held.append((time.monotonic() + args.hold_add, packet))
                        say(f"holding add product={props.get(b'PRODUCT', b'?').decode()} for {args.hold_add:g}s (fresh-attach mode)")
                        continue
                    sender.sendto(packet, (0, 2))
                    seen += 1
                    say(f"FORWARDED {props[b'ACTION'].decode()} product={props.get(b'PRODUCT', b'?').decode()} (#{seen})")
    os.close(pidfd)
    say('Container stopped. Relay finished.')


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        say('Relay stopped by user.')
    except (OSError, ValueError) as exc:
        say(f'RELAY ERROR: {exc}')
        sys.exit(1)
RELAY_PY_EOF
  cat > "$USBCAP" <<'USBCAP_PY_EOF'
#!/usr/bin/env python3
"""Full-payload USB capture for one bus, written as a pcap file Wireshark can open.

The text usbmon interface (debugfs) cuts every packet to about 32 bytes. The binary
interface (/dev/usbmonN) can return whole packets, so this reads it with the documented
MON_IOCX_GET ioctl and writes a standard pcap (link type 189, DLT_USB_LINUX, 48-byte
header). Needs root and the usbmon kernel module.

Usage: usbcap.py --bus 1 --out capture.pcap [--port 1-1.2 ...] [--snaplen 65535]

With --port, only packets of the device(s) on those USB ports are kept (the USB address of a device
changes every time it restarts, so it is looked up again in /sys as needed). Other devices on the bus,
such as a USB keyboard or mouse, are not recorded.
"""
import argparse
import ctypes
import fcntl
import os
import signal
import struct
import sys
import time

HDR = struct.Struct('<QBBBBHbbqiiII8s')   # struct usbmon_packet (API0), 48 bytes
assert HDR.size == 48
MON_IOC_MAGIC = 0x92
IOC_WRITE = 1


def _iow(nr, size):
    return (IOC_WRITE << 30) | (size << 16) | (MON_IOC_MAGIC << 8) | nr


MON_IOCX_GET = _iow(6, 24)   # struct mon_bin_get is three 8-byte fields on 64-bit


def say(msg):
    print(time.strftime('%Y-%m-%d %H:%M:%S'), msg, flush=True)


class Stop(Exception):
    pass


_stop_seen = []


def _stop_handler(*_):
    # Only the first stop signal interrupts the capture. A second one (or one that arrives while the
    # file is being closed) used to escape as an ugly traceback and hide the final summary line.
    if _stop_seen:
        return
    _stop_seen.append(1)
    raise Stop()


def make_node(dev, bus):
    """The usbmon module normally makes /dev/usbmonN itself. If the node is missing, make it."""
    try:
        with open('/proc/devices') as f:
            major = None
            in_char = False
            for line in f:
                if line.startswith('Character devices'):
                    in_char = True
                elif line.startswith('Block devices'):
                    in_char = False
                elif in_char and line.split()[-1:] == ['usbmon']:
                    major = int(line.split()[0])
        if major is not None:
            os.mknod(dev, 0o600 | 0o020000, os.makedev(major, bus))
            say(f'made missing {dev} (major {major})')
    except Exception as exc:
        say(f'could not make {dev}: {exc}')


def open_monitor(dev, bus):
    """Open the monitor node, waiting a few seconds for the module and its device node to appear."""
    last = None
    for attempt in range(20):
        try:
            return os.open(dev, os.O_RDONLY)
        except OSError as exc:
            last = exc
            if attempt == 4 and not os.path.exists(dev):
                make_node(dev, bus)
            time.sleep(0.5)
    raise last


def port_devnum(port):
    try:
        with open(f'/sys/bus/usb/devices/{port}/devnum') as f:
            return int(f.read().strip())
    except (OSError, ValueError):
        return None


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--bus', type=int, required=True)
    ap.add_argument('--out', required=True)
    ap.add_argument('--snaplen', type=int, default=65535)
    ap.add_argument('--port', action='append', default=[], help='keep only this USB port (for example 1-1.2); repeatable')
    args = ap.parse_args()
    if os.geteuid() != 0:
        raise SystemExit('Run as root')
    if struct.calcsize('P') != 8:
        raise SystemExit('64-bit only')
    dev = f'/dev/usbmon{args.bus}'
    fd = open_monitor(dev, args.bus)
    hdr = ctypes.create_string_buffer(64)
    data = ctypes.create_string_buffer(args.snaplen)
    arg = struct.pack('<QQQ', ctypes.addressof(hdr), ctypes.addressof(data), args.snaplen)
    stop = []
    signal.signal(signal.SIGTERM, _stop_handler)
    signal.signal(signal.SIGINT, _stop_handler)
    count = 0
    nbytes = 0
    dropped = 0
    known = {0}            # address 0 is a device that has not been given an address yet
    last_look = 0.0

    def look():
        nonlocal last_look
        last_look = time.time()
        for prt in args.port:
            n = port_devnum(prt)
            if n is not None:
                known.add(n)

    if args.port:
        look()
        say(f'keeping only ports {", ".join(args.port)} (other USB devices are not recorded)')
    with open(args.out, 'wb') as out:
        out.write(struct.pack('<IHHiIII', 0xa1b2c3d4, 2, 4, 0, 0, args.snaplen + 48, 189))
        say(f'capturing {dev} -> {args.out}')
        try:
            while not stop:
                try:
                    fcntl.ioctl(fd, MON_IOCX_GET, arg)
                except InterruptedError:
                    continue
                except OSError as exc:
                    say(f'ioctl failed: {exc}')
                    raise SystemExit(2)
                raw = hdr.raw[:48]
                fields = HDR.unpack(raw)
                if args.port and fields[4] not in known:
                    if time.time() - last_look > 0.05:
                        look()
                    if fields[4] not in known:
                        dropped += 1
                        continue
                ts_sec, ts_usec, length, len_cap = fields[8], fields[9], fields[11], fields[12]
                cap = min(len_cap, args.snaplen)
                payload = data.raw[:cap]
                out.write(struct.pack('<IIII', ts_sec & 0xffffffff, max(ts_usec, 0), 48 + cap, 48 + length))
                out.write(raw)
                out.write(payload)
                out.flush()
                count += 1
                nbytes += cap
                if count == 1:
                    say('first packet captured: the monitor works')
                if count % 5000 == 0:
                    say(f'{count} packets, {nbytes} payload bytes')
        except Stop:
            pass
    say(f'stopped: {count} packets, {nbytes} payload bytes' + (f', {dropped} packets of other devices left out' if args.port else ''))


if __name__ == '__main__':
    try:
        main()
    except Stop:
        say('stopped')
    except OSError as exc:
        say(f'USBCAP ERROR: {exc}')
        sys.exit(1)
USBCAP_PY_EOF
  chmod 600 "$RELAY" "$USBCAP"
}

engine_vm_state() { # engine_vm_state user|root -> none | stopped | running | unknown (root without a cached password)
  local st
  if [[ "$1" == root ]]; then
    # Nothing is asked of sudo unless administrator mode is actually in play (keeps plain Windows password-free)
    [[ $EUID -eq 0 || "${ACTIVE_ENGINE:-}" == root || "$BASE_ENGINE" == root ]] || { echo none; return; }
    [[ $EUID -eq 0 ]] || sudo -n true 2>/dev/null || { echo unknown; return; }
    st="$(pm_r inspect -f '{{.State.Status}}' "$NAME" 2>/dev/null)" || { echo none; return; }
  else
    st="$(pm_u inspect -f '{{.State.Status}}' "$NAME" 2>/dev/null)" || { echo none; return; }
  fi
  [[ "$st" == running ]] && echo running || echo stopped
}
vm_state() { # either engine. prints: none | stopped | running | unknown
  local e s out=none
  for e in user root; do
    s="$(engine_vm_state "$e")"
    case "$s" in
      running) echo running; return;;
      unknown) [[ "${ACTIVE_ENGINE:-}" == root ]] && out=unknown;;
      stopped) [[ "$out" == none ]] && out=stopped;;
    esac
  done
  echo "$out"
}
set_active() { save_state ACTIVE_ENGINE "$ENGINE"; save_state ACTIVE_BOOT "$BOOT_ID"; ACTIVE_ENGINE="$ENGINE"; ACTIVE_BOOT="$BOOT_ID"; }
clear_active() { save_state ACTIVE_ENGINE ""; ACTIVE_ENGINE=""; }

# Windows counts as installed when setup finished cleanly, OR when the Windows disk exists and Windows' own last
# install step left its "finished" line in the Shared folder (covers a setup that was never confirmed with Enter).
installed() {
  [[ -n "$(compgen -G "$STORAGE/data.*")" ]] || return 1
  [[ "${INSTALLED:-0}" == 1 ]] && return 0
  if grep -qs 'OEM install.bat finished' "$SHARED/nerdzap-install.log" 2>/dev/null; then
    save_state INSTALLED 1; INSTALLED=1
    return 0
  fi
  return 1
}

locale_bits() { # prints REGION/KEYBOARD env args derived from the Deck's locale, e.g. en_GB.UTF-8 -> en-GB
  local l="${LC_ALL:-${LANG:-}}"
  if [[ "$l" =~ ^([a-z]{2})_([A-Z]{2}) ]]; then echo "${BASH_REMATCH[1]}-${BASH_REMATCH[2]}"; fi
}

run_container() { # run_container [usb-arguments-string]
  local usb_args="${1:-}" loc
  local -a mounts=() envs=() extra=()
  loc="$(locale_bits)"
  envs=(-e "VERSION=$WIN_VERSION" -e "RAM_SIZE=$RAM" -e "CPU_CORES=$CORES" -e "DISK_SIZE=$DISK"
        -e DISK_FMT=qcow2 -e ALLOCATE=N -e "USERNAME=$WIN_USER" -e "PASSWORD=$WIN_PASS" -e NETWORK=user -e LOG=Y)
  [[ -n "$loc" ]] && envs+=(-e "REGION=$loc" -e "KEYBOARD=$loc")
  local qargs="$usb_args"
  [[ -n "${EXTRA_QEMU:-}" ]] && qargs="${qargs:+$qargs }$EXTRA_QEMU"      # hidden: extra QEMU arguments for testing (config.env), kept alongside any USB arguments
  [[ -n "$qargs" ]] && envs+=(-e "ARGUMENTS=$qargs")
  if [[ -n "$usb_args" ]]; then
    mounts+=(-v /dev/bus/usb:/dev/bus/usb -v "$RUNTIME/udev:/run/udev:ro" --device-cgroup-rule 'c 189:* rwm')
  fi
  # hidden test hooks (config.env): EXTRA_ENV="A=1 B=2" adds container variables, EXTRA_PODMAN="--opt value" adds Podman options
  local kv; local -a hx=()
  if [[ -n "${EXTRA_ENV:-}" ]]; then read -r -a hx <<< "$EXTRA_ENV"; for kv in "${hx[@]}"; do envs+=(-e "$kv"); done; fi
  # Settings > Advanced: custom Podman options (if they stop Windows from starting, it is tried again without them)
  local -a tx=()
  if [[ -n "${EXTRA_PODMAN:-}" ]]; then read -r -a hx <<< "$EXTRA_PODMAN"; tx+=("${hx[@]}"); fi
  # hidden: the Deck's graphics device handed to the VM. It does nothing useful yet, so it is not in Settings; set EXP_GPU=1 in config.env to try it.
  if [[ "${EXP_GPU:-0}" == 1 ]]; then
    if [[ -d /dev/dri ]]; then envs+=(-e GPU=Y); extra+=(--device /dev/dri); else warn "The hidden GPU test is on but /dev/dri is missing; continuing without it."; fi
  fi
  RDP_PUBLISHED=0
  if touch_on; then
    if port_busy "$RDP_PORT"; then dbg "RDP port $RDP_PORT is busy: touch display unavailable this time"
    else extra+=(-p "127.0.0.1:$RDP_PORT:3389/tcp"); RDP_PUBLISHED=1; fi
  fi
  dbg "starting container: edition=$WIN_VERSION ram=$RAM cores=$CORES disk=$DISK usb='${usb_args}' locale=${loc:-default} gpu=${EXP_GPU:-0} extra_env='${EXTRA_ENV:-}' extra_podman='${EXTRA_PODMAN:-}' extra_qemu='${EXTRA_QEMU:-}'"
  local rc=0
  runq pm run -d --name "$NAME" --stop-timeout 120 --device /dev/kvm \
      -p 127.0.0.1:8006:8006 \
      -v "$STORAGE:/storage" -v "$OEM:/oem" -v "$SHARED:/shared" \
      "${mounts[@]}" "${envs[@]}" "${extra[@]}" "${tx[@]}" "${RUN_IMAGE:-$IMAGE}" || rc=$?
  if [[ $rc -ne 0 && ${#tx[@]} -gt 0 ]]; then
    warn "Windows did not start with your custom Podman options. Trying again without them."
    pm rm -f "$NAME" >/dev/null 2>&1 || true
    rc=0
    runq pm run -d --name "$NAME" --stop-timeout 120 --device /dev/kvm \
        -p 127.0.0.1:8006:8006 \
        -v "$STORAGE:/storage" -v "$OEM:/oem" -v "$SHARED:/shared" \
        "${mounts[@]}" "${envs[@]}" "${extra[@]}" "${RUN_IMAGE:-$IMAGE}" || rc=$?
  fi
  [[ $rc -eq 0 ]] && note_session
  return $rc
}

# What this Windows session really got. The VM software lowers the memory to what the Deck has free at the start, so the
# number in Settings can be more than Windows has. Read from the VM software's own log once it has said so.
SESSION_INFO="$BASE/session.info"
note_session() { # what this start asked for; the memory Windows really got is filled in by session_refresh
  mkdir -p "$BASE"
  printf 'asked_ram=%s\nrun_cores=%s\nram_got=\n' "${RAM%G}" "$CORES" > "$SESSION_INFO"
}
session_val() { sed -n "s/^$1=//p" "$SESSION_INFO" 2>/dev/null | head -1; }
session_refresh() { # called from the status poll while Windows runs: reads the memory Windows really got
  local got try; try="$SESSION_INFO.try"
  mkdir -p "$BASE"
  # session.info is written when Windows is started. If it is missing (an older start), make an empty one so the memory can still be found.
  [[ -f "$SESSION_INFO" ]] || printf 'asked_ram=\nrun_cores=\nram_got=\n' > "$SESSION_INFO"
  got="$(session_val ram_got)"
  [[ -n "$got" ]] && return 0
  # look at most every 10 seconds (reading the VM software's log is not free), but keep looking while Windows runs:
  # a first-time setup takes much longer than any fixed time limit
  if [[ -f "$try" ]]; then (( $(date +%s) - $(stat -c %Y "$try" 2>/dev/null || echo 0) < 10 )) && return 0; fi
  : > "$try"
  local -a P=(podman --root "$PODROOT_U" --runroot "$PODRUN_U")
  if [[ "${ACTIVE_ENGINE:-}" == root ]]; then P=(podman --root "$PODROOT" --runroot "$PODRUN"); [[ ${#SUDO[@]} -gt 0 ]] && P=("${SUDO[@]}" -n "${P[@]}"); fi
  # the memory the virtual machine really has is on its own command line (-m 6G, -m 6144M or -m 6144)
  local m; m="$("${P[@]}" top "$NAME" args 2>/dev/null | grep -o -- ' -m [0-9][0-9.]*[MmGg]\?' | head -1 | sed 's/^ -m //')"
  case "$m" in
    *[Gg]) got="${m%[Gg]}";;
    *[Mm]) got="$(awk -v v="${m%[Mm]}" 'BEGIN{printf "%.1f", v/1024}')";;
    [0-9]*) got="$(awk -v v="$m" 'BEGIN{printf "%.1f", v/1024}')";;
  esac
  # older VM software also said it in its log
  [[ -n "$got" ]] || got="$("${P[@]}" logs "$NAME" 2>&1 | grep -o 'Allocated [0-9.]* GB of RAM' | tail -1 | grep -o '[0-9][0-9.]*' | head -1)"
  [[ -n "$got" ]] || return 0
  printf 'asked_ram=%s\nrun_cores=%s\nram_got=%s\n' "$(session_val asked_ram)" "$(session_val run_cores)" "$got" > "$SESSION_INFO.tmp" && mv "$SESSION_INFO.tmp" "$SESSION_INFO"
}


graceful_stop_vm() { # stops the VM whichever engine started it
  [[ "${ACTIVE_ENGINE:-}" == root ]] && need_sudo "to stop the Windows that has a USB device attached"
  local e s
  for e in user root; do
    s="$(engine_vm_state "$e")"
    if [[ "$s" == running ]]; then
      say "  Asking Windows to shut down (up to 2 minutes). Please wait..."
      if [[ "$e" == root ]]; then runq pm_r stop -t 120 "$NAME"; else runq pm_u stop -t 120 "$NAME"; fi
    fi
    if [[ "$s" == running || "$s" == stopped ]]; then
      if [[ "$e" == root ]]; then pm_r rm -f "$NAME" >/dev/null 2>&1 || true; else pm_u rm -f "$NAME" >/dev/null 2>&1 || true; fi
    fi
  done
  guacd_stop
  return 0
}

# In the window every progress line is kept (the page counts the finished parts); in a terminal only the last few show.
pull_image() {
  local rc
  if [[ "$GUI" == 1 ]]; then pm pull "$IMAGE" 2>&1 | tee -a "$LOGS/commands.log"; rc=${PIPESTATUS[0]}
  else pm pull "$IMAGE" 2>&1 | tee -a "$LOGS/commands.log" | tail -n 3; rc=${PIPESTATUS[0]}; fi
  return "$rc"
}

pull_failed() {
  if tail -n 60 "$LOGS/commands.log" 2>/dev/null | grep -qiE 'toomanyrequests|rate limit'; then
    die "Docker Hub is limiting downloads from your internet connection (it counts everyone sharing the same address). Wait a while, or try on another connection, then run it again."
  fi
  die "The download failed. Check your internet connection and free space, then try again."
}

# Make sure the current engine has the VM software. For a USB session the administrator-mode store gets a copy of
# the normal-user download instead of downloading it a second time.
ensure_image() {
  pm image exists "$IMAGE" 2>/dev/null && return 0
  if [[ "$ENGINE" == root && "$BASE_ENGINE" == user ]] && pm_u image exists "$IMAGE" 2>/dev/null; then
    say "  Preparing for the controller update (one time)..."
    if pm_u save "$IMAGE" 2>>"$LOGS/commands.log" | pm_r load >>"$LOGS/commands.log" 2>&1 && pm image exists "$IMAGE" 2>/dev/null; then return 0; fi
    warn "Copying did not work; downloading it instead."
  fi
  say "  Downloading the VM software..."
  pull_image || pull_failed
}

open_console() {
  if [[ "$GUI" == 1 ]]; then say "  Windows screen: shown in the DeckVM window."; return 0; fi
  say "  Windows screen: http://127.0.0.1:8006  (opens in your browser)"
  command -v xdg-open >/dev/null && ( xdg-open http://127.0.0.1:8006 >/dev/null 2>&1 & ) || true
}

# ---- touch-aware display helper (guacd). Best effort: if anything here fails, Windows still works with the plain display.
guacd_stop() { pmg rm -f -t 1 "$GUACD_NAME" >/dev/null 2>&1 || true; }
start_guacd() {
  touch_on && [[ "${RDP_PUBLISHED:-0}" == 1 ]] || return 0
  mkdir -p "$LOGS"
  local -a g
  if [[ "$BASE_ENGINE" == root ]]; then g=("${SUDO[@]}" podman --root "$PODROOT" --runroot "$PODRUN")
  else g=(podman --root "$PODROOT_U" --runroot "$PODRUN_U"); fi
  if ! "${g[@]}" image exists "$GUACD_IMAGE" 2>/dev/null; then
    say "  Getting the touch keyboard support (one time, about 100 MB)..."
    if ! timeout 400 "${g[@]}" pull "$GUACD_IMAGE" >> "$LOGS/guacd.log" 2>&1; then
      warn "Could not download the touch keyboard support. Windows works without it."
      event "GUACD_PULL_FAILED" "image=$GUACD_IMAGE"; return 0
    fi
    event "GUACD_PULLED" "image=$GUACD_IMAGE"
  fi
  guacd_stop
  # --network host so it can reach the RDP port on 127.0.0.1; -b/-l make it listen on 127.0.0.1 only (later options win
  # over the image's own -b 0.0.0.0). No capabilities and no new privileges: it only speaks network protocols.
  if "${g[@]}" run -d --rm --name "$GUACD_NAME" --network host --cap-drop all --security-opt no-new-privileges \
       "$GUACD_IMAGE" -b 127.0.0.1 -l "$GUACD_PORT" >> "$LOGS/guacd.log" 2>&1; then
    event "GUACD_STARTED" "port=$GUACD_PORT rdp=$RDP_PORT"
  else
    warn "Touch keyboard support did not start. Windows works without it."; event "GUACD_START_FAILED" ""
  fi
}
set_stage() { mkdir -p "$BASE"; printf '%s\n' "$1" > "$STAGEFILE"; }

prepare_dirs() {
  ensure_user_owned
  mkdir -p "$STORAGE" "$RUNTIME/udev" "$OEM" "$SHARED" "$LOGS"
  touch "$RUNTIME/udev/control"
  extract_helpers
  write_oem
}

# ------------------------------------------------------------------- setup ----
setup_choose() { # interactive questions; sets and saves WIN_VERSION RAM
  step "Choose a Windows version"
  local i=0 e code ename esize enote etested
  for e in "${EDITIONS[@]}"; do
    i=$((i+1))
    IFS='|' read -r code ename esize enote etested <<<"$e"
    printf '  %d) %-17s ~%s GB download\n       %s\n' "$i" "$ename" "$esize" "$enote"
  done
  ask "  Number" "1"
  [[ "$REPLY" =~ ^[0-9]+$ && "$REPLY" -ge 1 && "$REPLY" -le ${#EDITIONS[@]} ]] || die "Please type one of the numbers shown."
  e="${EDITIONS[$((REPLY-1))]}"
  IFS='|' read -r code ename esize enote etested <<<"$e"
  save_conf WIN_VERSION "$code"; WIN_VERSION="$code"
  ok "Chosen: $ename"

  step "Memory for Windows"
  local ram_gb; ram_gb=$(awk '/MemTotal/ {printf "%d", $2/1024/1024}' /proc/meminfo)
  say "  Your Deck has about ${ram_gb} GB. Windows takes its share while it runs; SteamOS keeps the rest."
  ask "  GB for Windows (3 to 10)" "6"
  [[ "$REPLY" =~ ^[0-9]+$ && "$REPLY" -ge 3 && "$REPLY" -le 10 ]] || die "Please type a number between 3 and 10."
  save_conf RAM "${REPLY}G"; RAM="${REPLY}G"
}

ensure_creds() {
  if ! grep -q '^WIN_PASS=' "$CONF" 2>/dev/null; then
    save_conf WIN_USER "$DEFAULT_WIN"
    save_conf WIN_PASS "$DEFAULT_WIN"   # simple on purpose: it has to be typed on a lock screen. Windows is only reachable from this Deck (127.0.0.1)
  fi
  save_conf WIN_VERSION "$WIN_VERSION"; save_conf RAM "$RAM"; save_conf CORES "$CORES"; save_conf DISK "$DISK"
  load_conf
}

# GUI mode: instead of "press Enter", wait for Windows' own "install finished" line in the Shared folder (or the
# GUI's "I can see the desktop" button).
wait_for_windows_install() {
  rm -f "$UI_CONTINUE"
  local t0; t0=$(date +%s)
  while true; do
    if grep -qs 'OEM install.bat finished' "$SHARED/nerdzap-install.log" 2>/dev/null; then
      info "Windows reported that its setup has finished."; sleep 25; return 0
    fi
    if [[ -f "$UI_CONTINUE" ]]; then rm -f "$UI_CONTINUE"; return 0; fi
    case "$(engine_vm_state "$ENGINE")" in none|stopped) die "Windows stopped before its setup finished. Choose 'Copy report' and send it to NerdZap.";; esac
    (( $(date +%s) - t0 > 10800 )) && die "Windows setup is taking far too long (3 hours). Choose 'Copy report' and send it to NerdZap."
    sleep 5
  done
}

setup_core() { # download and install Windows with the settings already chosen; ends with Windows shut down
  ensure_creds
  ok "Settings: $(edition_name "$WIN_VERSION"), ${RAM} memory, ${CORES} cores, ${DISK} disk"
  info "Windows login (if it ever asks): user $WIN_USER, password $WIN_PASS (it is also in $CONF)"
  prepare_dirs
  if [[ -n "$(list_ms)" ]]; then warn "An Xbox device is plugged in. Unplug it until Windows has finished installing."; fi

  set_stage "pull"
  step "Downloading the virtual machine software"
  local t0; t0=$(date +%s)
  pull_image || pull_failed
  event "IMAGE_PULLED" "seconds=$(( $(date +%s) - t0 )) image=$IMAGE digest=$(pm image inspect -f '{{.Digest}}' "$IMAGE" 2>/dev/null)"

  step "Starting Windows setup"
  rm -f "$SHARED/nerdzap-install.log"
  pm rm -f "$NAME" >/dev/null 2>&1 || true
  run_container "" || { port_busy 8006 && warn "Port 8006 is in use. Do you have another copy running?"; die "Windows could not be started."; }
  set_active
  set_pmv
  bg_start container "${PMV[@]}" logs -f "$NAME"
  bg_start inhibit systemd-inhibit --what=sleep:idle --mode=block --who=NerdZapDeckVM --why="Windows VM running" bash -c "$SLEEP_HOLD"
  start_guacd
  event "INSTALL_STARTED" "edition=$WIN_VERSION ram=$RAM cores=$CORES disk=$DISK"
  set_stage "install"
  open_console
  if [[ "$GUI" == 1 ]]; then
    wait_for_windows_install
    step "Finishing up"
    save_state INSTALLED 1; INSTALLED=1
    event "INSTALL_DONE" "edition=$WIN_VERSION (left running)"
    set_stage "ready"
    ok "Windows is installed and running."
    return 0
  fi
  say
  say "  Windows now installs by itself and restarts a few times. Watch it in the browser window."
  say "  When you can see the Windows DESKTOP (the picture with the taskbar), come back here."
  say
  pause "  Press Enter once the Windows desktop is showing... "
  step "Finishing up"
  graceful_stop_vm
  bg_stop_all
  clear_active
  save_state INSTALLED 1; INSTALLED=1
  event "INSTALL_DONE" "edition=$WIN_VERSION"
  ok "Windows is installed and shut down."
}

cmd_setup() {
  stage_begin "setup"
  step "Set up Windows"
  say "  This downloads Windows and installs it into a virtual machine. It takes a while,"
  say "  and the Deck must stay awake and plugged in. Nothing on your Deck's own system is changed."
  step "Checking your Deck"
  preflight || die "Your Deck is not ready. Fix the red items above and run this again."
  load_conf 2>/dev/null || true; load_state
  if installed; then
    warn "Windows is already set up here ($(edition_name "${WIN_VERSION:-11}"))."
    confirm "  Delete it and start again?" n || { say "  Keeping the existing Windows."; return 0; }
    graceful_stop_vm
    rm_tree "$STORAGE"; save_state INSTALLED 0; INSTALLED=0
  fi
  setup_choose
  setup_core
  ok "Next: use the menu to start it, or run the Xbox controller update."
  stage_end 0
}

# ------------------------------------------------------------------- start ----
require_installed() {
  load_conf 2>/dev/null || true; load_state
  installed || die "Windows is not set up yet. Choose 'Set up Windows' first."
}

start_common() { # start_common usb_args
  local usb_args="${1:-}"
  prepare_dirs
  write_touchkb_bat
  ensure_image
  pm rm -f "$NAME" >/dev/null 2>&1 || true
  wait_port_free 8006 "${DECKVM_PORT_WAIT:-30}" || die "Something else is using port 8006 (the Windows screen), so Windows cannot start. A leftover Windows may still be running: choose Stop, or restart the Deck, then try again."
  # The port is sometimes still held for a few seconds after the previous Windows stopped, even when it looked free a
  # moment earlier. Try again a few times, and record who holds it so a report can show it.
  local try=1
  [[ "$ENGINE" == root ]] && wait_tw_clear
  until run_container "$usb_args"; do
    if [[ $try -lt 4 ]] && tail -n 5 "$LOGS/commands.log" 2>/dev/null | grep -qi 'address already in use'; then
      { echo "--- start attempt $try failed: port 8006 in use. Holders:"; ss -tanp 2>/dev/null | grep ':8006 '
        [[ "$ENGINE" == root ]] && sudo -n ss -tanp 2>/dev/null | grep ':8006 '
        ps -eo pid,etimes,args 2>/dev/null | grep -E 'conmon|pasta|rootlessport|slirp|qemu' | grep -v grep; } >> "$LOGS/commands.log" 2>&1
      event "PORT_RETRY" "attempt=$try engine=$ENGINE"
      pm rm -f "$NAME" >/dev/null 2>&1 || true
      if port_tw; then wait_tw_clear
      else say "  The Windows screen port is still busy. Trying again in a few seconds..."; sleep 5; fi
      try=$((try + 1)); continue
    fi
    port_busy 8006 && warn "Port 8006 is in use. Do you have another copy running?"
    die "Windows could not be started."
  done
  sleep 3
  local cpid; cpid="$(pm inspect -f '{{.State.Pid}}' "$NAME" 2>/dev/null)"
  [[ "${cpid:-0}" -gt 0 ]] || die "Windows did not start (see the report)."
  CPID="$cpid"
  event "CONTAINER_STARTED" "pid=$cpid engine=$ENGINE usb='${usb_args}'"
  set_active
  set_pmv
  bg_start container "${PMV[@]}" logs -f "$NAME"
  bg_start inhibit systemd-inhibit --what=sleep:idle --mode=block --who=NerdZapDeckVM --why="Windows VM running" bash -c "$SLEEP_HOLD"
  start_guacd
}

cmd_start() {
  stage_begin "start"
  require_installed
  [[ "$ENGINE" == root ]] && need_sudo "to run Windows in administrator mode"
  local vs; vs="$(vm_state)"
  if [[ "$vs" == unknown ]]; then need_sudo "to check the Windows that has a USB device attached"; vs="$(vm_state)"; fi
  if [[ "$vs" == running ]]; then
    if [[ "${ACTIVE_ENGINE:-$ENGINE}" == "$ENGINE" ]]; then ok "Windows is already running."; open_console; return 0; fi
    warn "Windows is already running with a USB device attached. Choose 'Stop Windows' first, then start it again."
    return 1
  fi
  step "Starting $(edition_name "$WIN_VERSION")"
  start_common ""
  ok "Windows is starting."
  open_console
  say "  When you are finished: shut Windows down from its Start menu, then choose 'Stop Windows' here."
  stage_end 0
}

# --------------------------------------------------------- USB / Xbox flows ----
# The USB watchers and the shortcuts re-run this script, so it must exist as a file (not be piped from curl).
SRC_URL="${DECKVM_SRC:-https://nerdzap.com/tools/deckvm/scripts/deckvm.sh}"
persist_self() { # make sure a copy of this script lives at $BASE/deckvm.sh and SELF points at a file
  mkdir -p "$BASE"
  local target="$BASE/deckvm.sh"
  if [[ -n "${SELF:-}" && -f "$SELF" ]]; then
    [[ "$SELF" == "$target" ]] || cp "$SELF" "$target"
  else
    curl -fsSL "$SRC_URL" -o "$target.tmp" || die "Could not save a copy of the script from $SRC_URL"
    mv "$target.tmp" "$target"
  fi
  chmod +x "$target"
  SELF="$target"
}
ensure_self() { [[ -n "${SELF:-}" && -f "$SELF" ]] && return 0; persist_self; }

# An Xbox controller that SteamOS's own driver has already woken up does not start properly for Windows: Windows lists
# it in Device Manager, but the Xbox Accessories app does not see it until the cable is pulled and plugged back in
# (the port has no power switching, so DeckVM cannot do that by software). With SteamOS's driver paused, a fresh
# plug-in goes straight to Windows. So the person is asked to do that once, before Windows starts.
# ---- software "replug" experiments. An Xbox controller that SteamOS's driver already woke up does not start properly for
# Windows (see ask_replug). These try to put it back to its power-on state without touching the cable. Not on by default:
# set SOFTRESET=gip|gipoff|disable|authorized|all in ~/deckvm/config.env (or DECKVM_SOFTRESET=... in a terminal) and start a
# controller session. The result of each step goes to the report timeline (SOFTRESET lines).
gip_send() { # gip_send PORT MODE_HEX  -> sends the GIP "set device state" command (05 20 seq 01 mode) to the controller.
  # Modes (the open-source xone driver's names): 00 on, 01 sleep, 04 off, 07 reset. Needs the host Xbox drivers unloaded.
  local port="$1" mode="$2" bn dn
  bn="$(cat "$SYSFS/$port/busnum" 2>/dev/null)"; dn="$(cat "$SYSFS/$port/devnum" 2>/dev/null)"
  [[ -n "$bn" && -n "$dn" ]] || { echo "not plugged in"; return 1; }
  "${SUDO[@]}" python3 -I - "$(printf '/dev/bus/usb/%03d/%03d' "$bn" "$dn")" "$SYSFS/$port" "$port" "$mode" <<'PYEOF'
import ctypes, fcntl, glob, os, struct, sys
dev, sysdir, port, mode = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4], 16)
ep = None
for d in sorted(glob.glob("%s/%s:1.0/ep_*" % (sysdir, port))):
    try:
        typ = open(d + "/type").read().strip(); dr = open(d + "/direction").read().strip()
        addr = int(open(d + "/bEndpointAddress").read().strip(), 16)
    except (OSError, ValueError):
        continue
    if typ == "Interrupt" and dr == "out":
        ep = addr
        break
if ep is None:
    print("no interrupt OUT endpoint on interface 0")
    sys.exit(2)
fd = os.open(dev, os.O_RDWR)
fcntl.ioctl(fd, 0x8004550F, struct.pack("I", 0))            # USBDEVFS_CLAIMINTERFACE 0
pkt = bytes([0x05, 0x20, 0x01, 0x01, mode])
buf = ctypes.create_string_buffer(pkt, len(pkt))
class BT(ctypes.Structure):
    _fields_ = [("ep", ctypes.c_uint), ("len", ctypes.c_uint), ("timeout", ctypes.c_uint), ("data", ctypes.c_void_p)]
bt = BT(ep, len(pkt), 1000, ctypes.cast(buf, ctypes.c_void_p))
try:
    fcntl.ioctl(fd, 0xC0185502, bytes(bt))                  # USBDEVFS_BULK (works for the interrupt endpoint)
    print("sent %s to endpoint 0x%02x" % (pkt.hex(), ep))
finally:
    try:
        fcntl.ioctl(fd, 0x80045510, struct.pack("I", 0))    # USBDEVFS_RELEASEINTERFACE 0
    except OSError:
        pass
    os.close(fd)
PYEOF
}

soft_reset_one() { # soft_reset_one PORT METHOD
  local port="$1" m="$2" hp out rc=0
  case "$m" in
    gip)        out="$(gip_send "$port" 07 2>&1)" || rc=$?;;
    gipoff)     out="$(gip_send "$port" 04 2>&1)" || rc=$?;;
    disable)    hp="$(readlink -f "$SYSFS/$port/port" 2>/dev/null)"
                if [[ -n "$hp" && -e "$hp/disable" ]]; then
                  out="$(printf 1 | "${SUDO[@]}" tee "$hp/disable" 2>&1 >/dev/null; sleep 2; printf 0 | "${SUDO[@]}" tee "$hp/disable" 2>&1 >/dev/null)" || rc=$?
                else out="this port has no disable switch"; rc=1; fi;;
    authorized) out="$(printf 0 | "${SUDO[@]}" tee "$SYSFS/$port/authorized" 2>&1 >/dev/null; sleep 2; printf 1 | "${SUDO[@]}" tee "$SYSFS/$port/authorized" 2>&1 >/dev/null)" || rc=$?;;
    *)          out="unknown method $m"; rc=1;;
  esac
  event "SOFTRESET" "method=$m port=$port rc=$rc $(tr '\n' ' ' <<<"$out")"
  return "$rc"
}

soft_reset() { # soft_reset PORT METHOD  (METHOD may be "all")
  local port="$1" method="$2" m before after i list restarted=0 first
  first="$(cat "$SYSFS/$port/devnum" 2>/dev/null)"
  [[ -r "$SYSFS/$port/idVendor" ]] || return 0
  [[ "$method" == all ]] && list="gip disable authorized" || list="$method"
  step "Restarting the controller"
  for m in $list; do
    before="$(cat "$SYSFS/$port/devnum" 2>/dev/null)"
    if soft_reset_one "$port" "$m"; then dbg "restart method $m: sent"; else dbg "$m is not available on this controller"; continue; fi
    for ((i = 0; i < 75; i++)); do [[ -r "$SYSFS/$port/idVendor" ]] && break; sleep 0.2; done   # wait for it to come back
    sleep 3
    after="$(cat "$SYSFS/$port/devnum" 2>/dev/null)"
    event "SOFTRESET_RESULT" "method=$m port=$port devnum_before=$before devnum_after=${after:-gone}"
    if [[ -n "$after" && "$after" != "${before:-$first}" ]]; then restarted=1; dbg "USB address ${before:-$first} to $after"; say "  The controller restarted."; fi
  done
  if [[ ! -r "$SYSFS/$port/idVendor" ]]; then
    warn "The controller has not come back yet. If it stays missing, unplug it and plug it back in."
  elif [[ $restarted == 0 ]]; then
    event "SOFTRESET_FALLBACK" "port=$port reason=no_restart_seen"
    ask_replug "$port"       # nothing restarted the controller by itself, so ask for the physical replug instead
  fi
  return 0
}

ask_replug() { # ask_replug PORT
  local port="$1" wait_s="${DECKVM_REPLUG_WAIT:-300}" orig i n=0
  [[ "$wait_s" -gt 0 ]] || return 0
  [[ -r "$SYSFS/$port/idVendor" ]] || return 0
  orig="$(cat "$SYSFS/$port/devnum" 2>/dev/null)"
  step "Plug the controller in again"
  say "  Unplug the controller's cable now, wait a second, then plug it back in."
  say "  This lets Windows see it properly. DeckVM carries on by itself once it sees it."
  event "REPLUG_ASKED" "port=$port"
  rm -f "$UI_SKIP"
  # a desktop pop-up as well, because the person may be looking at Windows or at nothing at all
  local nid=""
  if command -v notify-send >/dev/null 2>&1; then nid="$(notify-send -p -a DeckVM -t 20000 "DeckVM: unplug and replug your controller" "Pull the cable out, wait a second, then plug it back in." 2>/dev/null | head -n1)" || nid=""
  elif command -v kdialog >/dev/null 2>&1; then kdialog --passivepopup "Unplug the controller's cable, wait a second, then plug it back in." 20 --title "DeckVM" >/dev/null 2>&1 || true; fi
  # take the pop-up away again as soon as this step is over, so nobody thinks it still has to be done
  replug_notice_close() { [[ "$nid" =~ ^[0-9]+$ ]] && gdbus call --session --dest org.freedesktop.Notifications --object-path /org/freedesktop/Notifications --method org.freedesktop.Notifications.CloseNotification "$nid" >/dev/null 2>&1 || true; }
  for ((i = 0; i < wait_s * 5; i++)); do
    if [[ -e "$UI_SKIP" ]]; then rm -f "$UI_SKIP"; replug_notice_close; warn "Skipped. If the Xbox Accessories app does not list the controller, unplug the cable and plug it back in."; event "REPLUG_SKIPPED_BY_USER" "port=$port"; return 0; fi
    if [[ ! -r "$SYSFS/$port/idVendor" || "$(cat "$SYSFS/$port/devnum" 2>/dev/null)" != "$orig" ]]; then n=1; break; fi
    sleep 0.2
  done
  replug_notice_close
  if [[ $n == 0 ]]; then
    warn "The controller was not unplugged, so DeckVM carries on. If the Xbox Accessories app does not list it, unplug the cable and plug it back in."
    event "REPLUG_SKIPPED" "port=$port"
    return 0
  fi
  for ((i = 0; i < 300; i++)); do [[ -r "$SYSFS/$port/idVendor" ]] && break; sleep 0.2; done
  if [[ -r "$SYSFS/$port/idVendor" ]]; then
    sleep 2
    ok "Controller plugged in again"
    event "REPLUG_DONE" "port=$port"
  else
    warn "The controller did not come back. Plug it in again before Windows has started."
    event "REPLUG_MISSING" "port=$port"
  fi
}

start_with_usb() { # start_with_usb MODE(xbox|any)
  local mode="$1"
  # Windows apps cannot see USB devices from inside a Remote Desktop session (the touch display), only from the console one. So a USB session never uses it.
  NO_TOUCH_THIS_START=1
  ENGINE=root       # USB passthrough needs administrator rights; this is the only place the password is asked
  need_sudo "to hand the USB device to Windows"
  ensure_self
  require_installed
  graceful_stop_vm
  # USB redirection (default): build or check the helper image before anything on the Deck is touched
  REDIR_ON=0; RUN_IMAGE=""
  if [[ "$(usb_mode)" == redir ]]; then
    if ensure_redir_image; then REDIR_ON=1
    else
      warn "The USB redirector could not be prepared, so DeckVM uses the older way of handing over the device this time. (Details: commands.log)"
      event "REDIR_FALLBACK" "using usb-host"
    fi
  fi
  save_state REDIR_ON "$REDIR_ON"
  event "USB_MODE" "redirect=$REDIR_ON"
  step "Finding the device"
  # The window can hand over several devices at once: "port1,port2,..." (generic USB session only)
  local extra_list="" ep eline ei=1 anyms=0 extra_args=""
  local -a XP=() XV=() XI=()
  if [[ "${DECKVM_USB_PORT:-}" == *,* ]]; then extra_list="${DECKVM_USB_PORT#*,}"; DECKVM_USB_PORT="${DECKVM_USB_PORT%%,*}"; fi
  pick_usb "$mode"
  local bus="${PORT%%-*}" hport="${PORT#*-}" vid="${DEV_ID%%:*}"
  [[ "$vid" == 045e ]] && anyms=1
  for ep in ${extra_list//,/ }; do
    [[ "$ep" =~ ^[0-9]+-[0-9]+(\.[0-9]+)*$ ]] || continue
    [[ "$ep" == "$PORT" ]] && continue
    eline="$(list_usb | awk -v p="$ep" '$1==p {print; exit}')"
    if [[ -z "$eline" ]]; then warn "The device on port $ep is no longer plugged in. Skipping it."; continue; fi
    ei=$((ei + 1))
    XP+=("$ep"); XI+=("${USBDEV_ID}$ei"); XV+=("$(awk '{print $2}' <<<"$eline" | cut -d: -f1)")
    [[ "${XV[-1]}" == 045e ]] && anyms=1
    if [[ $REDIR_ON == 1 ]]; then extra_args+=" $(redir_args $((ei - 1)) "${USBDEV_ID}$ei")"
    else extra_args+=" -device usb-host,hostbus=${ep%%-*},hostport=${ep#*-},id=${USBDEV_ID}$ei"; fi
    ok "Also using: $(cut -d' ' -f3- <<<"$eline")"
  done
  save_state PORT "$PORT"; save_state BUS "$bus"; save_state DEV_ID "$DEV_ID"; save_state DEV_VENDOR "$vid"
  save_state EXTRA_PORTS "${XP[*]:-}"; EXTRA_PORTS="${XP[*]:-}"
  prepare_dirs
  : > "$LOGS/usb-timeline.log"

  local unloaded="${HOST_MODS_UNLOADED:-}" m
  USB_UNLOADED="$unloaded"; USB_ROLLBACK=1
  [[ "${GUI:-0}" == 1 ]] || trap '[[ -n "${USB_ROLLBACK:-}" && "$BASHPID" == "$$" ]] && usb_rollback; exit 130' INT TERM HUP
  if [[ $anyms == 1 ]]; then
    step "Releasing the controller from SteamOS"
    block_host_drivers
    for m in xpad xbox_gip; do
      if mod_loaded "$m"; then
        if runq "${SUDO[@]}" modprobe -r "$m"; then [[ ",$unloaded" == *",$m,"* ]] || unloaded+="$m,"; USB_UNLOADED="$unloaded"; save_state HOST_MODS_UNLOADED "$unloaded"; save_state ACTIVE_BOOT "$BOOT_ID"; else warn "Could not unload $m. Windows will still try to take the controller."; fi
      fi
    done
    ok "SteamOS can't use the controller until you press Stop"
  fi
  save_state HOST_MODS_UNLOADED "$unloaded"
  if [[ $anyms == 1 ]]; then
    # By default DeckVM restarts the controller by itself (tested: Windows then sees it). SOFTRESET=replug asks for the cable to be pulled instead.
    local sr="${DECKVM_SOFTRESET:-${SOFTRESET:-all}}"
    if [[ "$sr" =~ ^(gip|gipoff|disable|authorized|all)$ ]]; then soft_reset "$PORT" "$sr"; else ask_replug "$PORT"; fi
  fi
  event "HOST_PREPARED" "modules_unloaded=${unloaded:-none} port=$PORT host_driver_now=$(host_driver_of "$PORT")"
  sudo -n true 2>/dev/null || need_sudo "to keep the USB helpers running"
  bg_start usb-timeline bash "$SELF" _watch_usb
  bg_start kernel sudo -n env DECKVM_BASE="$BASE" bash "$SELF" _watch_kernel

  step "Starting Windows with the device attached"
  local uo="${DECKVM_USB_OPTS:-${USB_OPTS:-}}"
  [[ "$uo" =~ ^[A-Za-z0-9_=,.-]+$ ]] || uo=""     # extra usb-host options for experiments, for example guest-resets-all=true
  local fresh_on="${DECKVM_FRESH_ATTACH:-1}" xi; local -a relay_fresh=()
  if [[ $REDIR_ON == 1 ]]; then
    start_common "$(redir_args 0 "$USBDEV_ID")$extra_args"
    # the redirectors (one per device) hand the device to Windows and take it away again when it restarts; the watchdog only answers Stop/Reconnect
    bg_start redir sudo -n env DECKVM_BASE="$BASE" bash "$SELF" _redir "$PORT" "$USBDEV_ID" "$REDIR_PORT_BASE"
    for xi in "${!XP[@]}"; do
      bg_start "redir-${XP[$xi]}" sudo -n env DECKVM_BASE="$BASE" bash "$SELF" _redir "${XP[$xi]}" "${XI[$xi]}" $((REDIR_PORT_BASE + xi + 1))
    done
    bg_start watchdog sudo -n env DECKVM_BASE="$BASE" bash "$SELF" _watchdog
  else
    start_common "-device usb-host,hostbus=$bus,hostport=$hport,id=$USBDEV_ID${uo:+,$uo}$extra_args"
    [[ "$fresh_on" == 1 ]] && relay_fresh=(--hold-add 3)
    event "FRESH_ATTACH" "mode=$fresh_on"
    bg_start relay sudo -n systemd-inhibit --what=sleep:idle --mode=block --who=NerdZapDeckVM --why="USB relay" \
        python3 -u "$RELAY" --pid "$CPID" --port "$PORT" --vendor "$vid" "${relay_fresh[@]}"
    bg_start watchdog sudo -n env DECKVM_BASE="$BASE" DECKVM_FRESH_ATTACH="$fresh_on" bash "$SELF" _watchdog
    for xi in "${!XP[@]}"; do
      bg_start "relay-${XP[$xi]}" sudo -n systemd-inhibit --what=sleep:idle --mode=block --who=NerdZapDeckVM --why="USB relay" \
          python3 -u "$RELAY" --pid "$CPID" --port "${XP[$xi]}" --vendor "${XV[$xi]}" "${relay_fresh[@]}"
      bg_start "watchdog-${XP[$xi]}" sudo -n env DECKVM_BASE="$BASE" DECKVM_FRESH_ATTACH="$fresh_on" bash "$SELF" _watchdog "${XP[$xi]}" "${XI[$xi]}"
    done
  fi
  if [[ "${RESEARCH:-0}" == 1 ]]; then
    local cap; cap="$LOGS/usb-bus${bus}-$(date +%Y%m%d-%H%M%S).pcap"
    # The helpers must start with sudo themselves (see bg_start): a shell wrapper loses the password ticket and sudo -n then fails.
    sudo -n modprobe usbmon 2>/dev/null
    local -a capports=(--port "$PORT"); for xi in "${!XP[@]}"; do capports+=(--port "${XP[$xi]}"); done
    bg_start usbcap sudo -n python3 -u "$USBCAP" --bus "$bus" --out "$cap" "${capports[@]}"
    event "CAPTURE_START" "usb recording pcap bus=$bus ports=$PORT ${XP[*]:-} file=$cap"
  fi
  USB_ROLLBACK=""
  trap - INT TERM HUP
  sleep 1
  wd_alive || { warn "DeckVM can't reconnect the controller if it drops out. Make a report if the update fails."; event "WARN" "watchdog not running after start"; }
  if [[ "${RESEARCH:-0}" == 1 ]]; then
    sleep 2
    if grep -q "capturing /dev/usbmon" "$LOGS/usbcap.log" 2>/dev/null; then ok "USB recording is running"
    else
      warn "The USB recording did not start (see usbcap.log in the logs folder). Nothing is being recorded. The update itself is not affected."; event "WARN" "usbcap not running after start"
    fi
  fi
  ok "Windows is starting with the device attached"
  open_console
}

cmd_usb() {
  stage_begin "usb session"
  step "Windows with a USB device"
  say "  Plug the device in first. It disappears from SteamOS while Windows owns it and returns when you stop."
  start_with_usb any
  say
  say "  Use the device in Windows. When finished: shut Windows down, then choose 'Stop Windows' here."
  stage_end 0
}

cmd_xbox() {
  stage_begin "xbox update"
  load_conf 2>/dev/null || true; load_state
  step "Xbox controller firmware update"
  say "  What you need: a USB DATA cable, and the controller's batteries in (or its own cable power)."
  say "  Windows takes over the controller for the update, so it is not usable in SteamOS meanwhile."
  if ! installed; then
    say
    warn "Windows is not set up yet."
    confirm "  Set up Windows 11 Pro now? (about 30 to 60 minutes, mostly downloading)" y || { say "  OK. Run 'Set up Windows' when you are ready."; return 0; }
    cmd_setup || return 1
    load_conf; load_state
    installed || die "Setup did not finish."
    say
    ok "Windows is ready. Plug in your controller now."
    pause "  Press Enter when the controller is plugged in with its USB cable... "
  elif [[ "${WIN_VERSION:-11}" != 11 && "${WIN_VERSION:-11}" != tiny11 && "$GUI" != 1 ]]; then
    warn "Your Windows is '$(edition_name "$WIN_VERSION")'. The Xbox Accessories app needs the Microsoft Store and a recent Windows, so it may not install here. Windows 11 Pro or Tiny11 are the best choices."
    confirm "  Continue anyway?" n || return 0
  fi
  start_with_usb xbox
  if [[ "$GUI" == 1 ]]; then stage_end 0; return 0; fi
  cat <<EOF

  ----------------------------------------------------------------------
  IN THE WINDOWS WINDOW (your browser):
   1. Wait for the desktop. Double-click "Install Xbox Accessories" (skip if it is already
      installed). The Microsoft Store opens: press Get. If it asks you to sign in, cancel.
   2. Open Xbox Accessories from the Start menu. If "Failed to sign in using Gaming Runtime
      Services" appears, press Cancel (sometimes 3 times, and it can come back as you move
      around the app; just cancel each time). Your controller should appear.
   3. Press the three dots (More options) under the controller, then Update now.
      DO NOT touch the cable or the Deck's power button.
      The controller will restart itself a few times. That is normal.
   4. If it says 100% then "failed", wait a minute. If it still says failed, unplug the
      controller and plug it back in; it should say up to date.
  ----------------------------------------------------------------------
EOF
  pause "  When the update is done, press Enter here to shut Windows down and give your controller back to SteamOS... "
  cmd_stop
  say
  say "  Unplug the controller and plug it in again. Your Deck sees the updated controller."
  say "  Bluetooth: pair it again in SteamOS if it does not reconnect."
  stage_end 0
}

# ------------------------------------------- hooks for the local GUI (machine-readable) ----
cmd_status_kv() { # key=value lines, no logging; used by the GUI
  NOLOG=1
  load_conf 2>/dev/null || true; load_state
  local inst=0 vs web=0 usbname="" owner=""
  # read-only version of installed(): the GUI polls this while a job may be writing the state file
  if [[ -n "$(compgen -G "$STORAGE/data.*")" ]] && { [[ "${INSTALLED:-0}" == 1 ]] || grep -qs 'OEM install.bat finished' "$SHARED/nerdzap-install.log" 2>/dev/null; }; then inst=1; fi
  vs="$(vm_state 2>/dev/null)"
  port_busy 8006 && web=1
  if [[ "$vs" == unknown && $web == 1 ]]; then vs=running; fi
  if [[ "${ACTIVE_ENGINE:-}" == root && -n "${PORT:-}" && "$vs" == running ]]; then
    owner="$(host_driver_of "$PORT" 2>/dev/null)"
    [[ -r "$SYSFS/$PORT/idVendor" ]] || owner="unplugged"
    usbname="${DEV_ID:-}"
  fi
  printf 'version=%s\n' "$TOOL_VERSION"
  printf 'installed=%s\n' "$inst"
  printf 'edition=%s\n' "${WIN_VERSION:-11}"
  printf 'edition_name=%s\n' "$(edition_name "${WIN_VERSION:-11}")"
  printf 'vm=%s\n' "$vs"
  printf 'web=%s\n' "$web"
  printf 'engine=%s\n' "${ACTIVE_ENGINE:-}"
  printf 'usb_port=%s\n' "${PORT:-}"
  printf 'usb_session=%s\n' "$([[ "${ACTIVE_ENGINE:-}" == root && "$vs" == running && -n "${PORT:-}" ]] && echo 1 || echo 0)"
  printf 'usb_ports=%s\n' "$([[ "$vs" == running && "${ACTIVE_ENGINE:-}" == root ]] && session_ports | awk 'NF{printf "%s ", $1}')"
  printf 'driver_block=%s\n' "$([[ -e "$MODCONF_ETC" ]] && echo 1 || echo 0)"
  # Windows (QEMU) died by itself a short while ago: the last lines of its log say so and the log was written in the last 15 minutes
  local crash=0 cl="$LOGS/container.log"
  if [[ "$vs" != running && -s "$cl" ]] && (( $(date +%s) - $(stat -c %Y "$cl" 2>/dev/null || echo 0) < 900 )) && tail -n 6 "$cl" 2>/dev/null | grep -q 'QEMU exited unexpectedly'; then crash=1; fi
  printf 'crash=%s\n' "$crash"
  printf 'capture=%s\n' "$([[ "${RESEARCH:-0}" == 1 && "$vs" == running ]] && pgrep -f 'usbcap\.py' >/dev/null 2>&1 && echo 1 || echo 0)"
  printf 'usb_id=%s\n' "$usbname"
  printf 'usb_owner=%s\n' "$owner"
  printf 'ram=%s\ncores=%s\ndisk=%s\nresearch=%s\nxboxapp=%s\ntouch=%s\n' "${RAM:-6G}" "${CORES:-4}" "${DISK:-40G}" "${RESEARCH:-0}" "${XBOXAPP:-0}" "$(touch_on && echo 1 || echo 0)"
  # what the running Windows really got (memory is lowered to what the Deck had free at the start), and the Deck's free memory now
  if [[ "$vs" == running ]]; then
    session_refresh
    printf 'run_ram_asked=%s\nrun_ram=%s\nrun_cores=%s\n' "$(session_val asked_ram)" "$(session_val ram_got)" "$(session_val run_cores)"
  fi
  printf 'x_env=%s\nx_podman=%s\nx_qemu=%s\n' "${EXTRA_ENV:-}" "${EXTRA_PODMAN:-}" "${EXTRA_QEMU:-}"
  printf 'mem_free_gb=%s\n' "$(awk '/MemAvailable/ {printf "%.1f", $2/1024/1024}' /proc/meminfo)"
  # was this Windows session started with the touch display? (the remote desktop port is only published when it was)
  printf 'touch_session=%s\n' "$([[ "$vs" == running ]] && port_busy "$RDP_PORT" && echo 1 || echo 0)"
  printf 'free_gb=%s\n' "$(free_gb "$HOME")"
  printf 'stage=%s\n' "$(cat "$STAGEFILE" 2>/dev/null)"
  printf 'rootless=%s\n' "${ROOTLESS:-1}"
}

cmd_devices_kv() { # one line per external USB device: port|id|name|microsoft(0/1)
  NOLOG=1
  local port id name ms internal rem
  while read -r port id name; do
    [[ -n "$port" ]] || continue
    ms=0; [[ "$id" == 045e:* ]] && ms=1
    internal=0
    rem="$(cat "$SYSFS/$port/removable" 2>/dev/null || echo unknown)"
    [[ "$rem" == "fixed" || "$id" == 28de:* ]] && internal=1
    printf 'dev=%s|%s|%s|%s|%s\n' "$port" "$id" "$name" "$ms" "$internal"
  done < <(list_usb all)
}

cmd_set() { # set KEY VALUE  (validated; the GUI's settings panel)
  local k="${1:-}" v="${2:-}"
  load_conf 2>/dev/null || true
  case "$k" in
    ram)   [[ "$v" =~ ^[0-9]+$ && "$v" -ge 3 && "$v" -le 10 ]]   || die "Memory must be 3 to 10 GB."; save_conf RAM "${v}G";;
    cores) [[ "$v" =~ ^[0-9]+$ && "$v" -ge 1 && "$v" -le 8 ]]    || die "Cores must be 1 to 8."; save_conf CORES "$v";;
    disk)  [[ "$v" =~ ^[0-9]+$ && "$v" -ge 30 && "$v" -le 256 ]] || die "Disk must be 30 to 256 GB."; save_conf DISK "${v}G";;
    expgpu) [[ "$v" == 0 || "$v" == 1 ]] || die "That setting must be 0 or 1."; save_conf EXP_GPU "$v";;
    extra_env) save_conf EXTRA_ENV "$v";;       # hidden test hooks: free text, an empty value clears them
    extra_podman) save_conf EXTRA_PODMAN "$v";;
    extra_qemu) save_conf EXTRA_QEMU "$v";;
    research) [[ "$v" == 0 || "$v" == 1 ]] || die "USB recording must be 0 or 1."; save_conf RESEARCH "$v";;
    touch) [[ "$v" == 0 || "$v" == 1 ]] || die "Touch display must be 0 or 1."; save_conf TOUCH "$v";;
    *) die "Unknown setting.";;
  esac
  ok "Saved. It applies the next time Windows starts."
}

# Take the USB device(s) out of the running Windows and put them back, like unplugging and replugging.
cmd_reattach() {
  load_conf 2>/dev/null || true; load_state
  [[ "${ACTIVE_ENGINE:-}" == root && -n "${PORT:-}" ]] || die "There is no USB session running."
  ENGINE=root
  step "Reconnecting the device to Windows"
  local done_it=0
  if ! sudo -n true 2>/dev/null && wd_alive; then
    say "  Reconnecting the controller..."
    if wd_request reattach 90; then done_it=1; else warn "Using your password instead."; fi
  fi
  if [[ $done_it == 0 ]]; then
    need_sudo "to reconnect the USB device"
    [[ "$(engine_vm_state root)" == running ]] || die "Windows is not running."
    reattach_now | sed 's/^/  /' || die "The device is not plugged in. Plug it in, wait a second, then try again."
  fi
  ok "Done. Give Windows a few seconds to notice it."
  say "  If the Xbox Accessories app still doesn't list your controller, unplug the cable and plug it back in."
}

# -------------------------------------------------------------------- stop ----
cmd_stop() {
  load_state
  stage_begin "stop"
  local rooted=0 viahelper=0 waited=0
  if root_traces; then
    rooted=1
    if sudo -n true 2>/dev/null; then :
    elif [[ "${ACTIVE_ENGINE:-}" == root ]] && wd_alive; then viahelper=1   # the session helper already has permission
    else need_sudo "to give the USB device back to SteamOS"; fi
  fi
  step "Stopping Windows and restoring SteamOS"
  say "  If Windows is still running, shut it down from its Start menu first (the script also asks it to)."
  if [[ $viahelper == 1 ]]; then
    say "  Asking Windows to shut down (up to 2 minutes). Please wait..."
    wd_request stop 170 || { warn "The helper did not answer in time. Switching Windows off and using your password instead."; viahelper=0; waited=1; need_sudo "to give the USB device back to SteamOS"; }
  fi
  if [[ $viahelper == 0 ]]; then
    if [[ ${waited:-0} == 1 ]]; then quick_stop_all; else graceful_stop_vm; fi   # already waited once: do not wait another 2 minutes
    sleep 1
  fi
  bg_stop_all
  if [[ $rooted == 1 ]]; then
    if [[ $viahelper == 0 ]]; then
      unblock_host_drivers
      local m restore="${HOST_MODS_UNLOADED:-}"
      for m in ${restore//,/ }; do
        runq "${SUDO[@]}" modprobe "$m" && event "HOST_DRIVER_RESTORED" "$m" || warn "Could not reload $m. A restart of the Deck fixes this."
      done
    fi
    save_state HOST_MODS_UNLOADED ""
    [[ $viahelper == 0 ]] && fix_ownership
  fi
  clear_active
  event "STOPPED" "windows disk kept in $STORAGE"
  ok "Stopped. Your Windows is kept for next time."
  stage_end 0
}

# Stop and remove the VM in either engine without waiting for Windows to shut down nicely (used when a job is cancelled).
quick_stop_all() {
  local e s
  for e in user root; do
    s="$(engine_vm_state "$e")"
    [[ "$s" == none || "$s" == unknown ]] && continue
    if [[ "$e" == root ]]; then runq pm_r stop -t 5 "$NAME"; pm_r rm -f "$NAME" >/dev/null 2>&1 || true
    else runq pm_u stop -t 5 "$NAME"; pm_u rm -f "$NAME" >/dev/null 2>&1 || true; fi
  done
  guacd_stop
}

# Hidden: tidy up after a job was cancelled from the window. _cancelclean JOB keep|delete
cmd__cancelclean() {
  local what="${1:-}" keep="${2:-keep}"
  load_conf 2>/dev/null || true; load_state
  stage_begin "cancel"
  step "Cancelling and cleaning up"
  case "$what" in
    xbox|usb|stop)
      if root_traces; then need_sudo "to put SteamOS's controller drivers back"; fi
      ENGINE=root
      quick_stop_all
      bg_stop_all
      if root_traces; then
        unblock_host_drivers
        local m
        for m in ${HOST_MODS_UNLOADED//,/ }; do runq "${SUDO[@]}" modprobe "$m" || true; done
        save_state HOST_MODS_UNLOADED ""
        fix_ownership
      fi
      clear_active
      if [[ "$what" == stop ]]; then ok "Windows was switched off. Your Windows and its files are kept, and SteamOS has its controller drivers back."
      else ok "Cancelled. SteamOS has its controller drivers back."; fi
      ;;
    auto|setup|start)
      ENGINE="$BASE_ENGINE"
      quick_stop_all
      bg_stop_all
      if [[ "$what" != start ]] && ! installed; then
        if [[ "$keep" == delete ]]; then
          rm_tree "$STORAGE"
          ok "Cancelled. The partly downloaded Windows was deleted."
        else
          find "$STORAGE" -maxdepth 1 -type f \( -name 'data.*' -o -name 'windows.*' -o -name '*.qcow2' -o -name '*.img' \) -delete 2>/dev/null
          ok "Cancelled. The files downloaded so far are kept, so the next try starts faster."
        fi
        clear_active; save_state INSTALLED 0
      else
        ok "Cancelled."
      fi
      ;;
    *) say "  Nothing to clean up." ;;
  esac
  stage_end 0
}

# Windows tools used by buttons in the window
cmd_eject() { # eject any disc (the install helper disc) that is attached to the running Windows
  load_conf 2>/dev/null || true; load_state
  [[ "$(vm_state)" == running ]] || die "Windows is not running."
  if [[ "${ACTIVE_ENGINE:-}" == root ]]; then
    need_sudo "to reach the running Windows"; ENGINE=root
  else ENGINE="${ACTIVE_ENGINE:-$BASE_ENGINE}"; fi
  step "Ejecting the install disc"
  local devs d n=0
  devs="$(qmon "info block" | awk '/^[^ =]/ {hdr=$1} /Removable device:/ {print hdr}')"
  for d in $devs; do
    [[ "$d" =~ ^[A-Za-z0-9_.-]+$ ]] || continue
    n=$((n + 1)); say "  Ejecting $d"
    qmon "eject -f $d" | sed 's/^/    /'
  done
  if [[ $n -eq 0 ]]; then say "  No disc is attached to Windows right now. The D: drive you may have seen is gone, or comes from somewhere else."; else ok "Done. Windows may take a few seconds to notice."; fi
}
cmd_open_shared() {
  mkdir -p "$SHARED"
  command -v xdg-open >/dev/null 2>&1 || die "No file manager found. The folder is $SHARED"
  ( setsid nohup xdg-open "$SHARED" >/dev/null 2>&1 & )
  ok "Opened the Shared folder (Z: in Windows): $SHARED"
}

# ------------------------------------------------------------------ status ----
cmd_status() {
  load_conf 2>/dev/null || true; load_state
  step "Status"
  say "  Windows set up : $(installed && echo "yes ($(edition_name "$WIN_VERSION"))" || echo no)"
  say "  Windows running: $(vm_state)   (mode: ${ACTIVE_ENGINE:-$BASE_ENGINE}$([[ "${ACTIVE_ENGINE:-}" == root && "$BASE_ENGINE" == user ]] && echo ', USB session'))"
  say "  Settings       : memory ${RAM:-6G}, cores ${CORES:-4}, disk ${DISK:-40G}, USB recording $([[ "${RESEARCH:-0}" == 1 ]] && echo on || echo off)"
  say "  Free space     : $(free_gb "$HOME") GB"
  if [[ "$(vm_state)" == running ]]; then
    say "  Attached USB   :"
    local sp; sp="${PORT:-}"
    [[ -n "$sp" && -r "$SYSFS/$sp/idVendor" ]] && say "     port $sp, owner now: $(host_driver_of "$sp")  (usbfs = Windows has it)"
    say "  Controller drop-outs seen this session: $(grep -c 'no external USB device present' "$LOGS/usb-timeline.log" 2>/dev/null || echo 0)"
    tail -n 4 "$LOGS/watchdog.log" 2>/dev/null | sed 's/^/     watchdog: /'
  fi
}

# ---------------------------------------------------------------- settings ----
cmd_settings() {
  load_conf 2>/dev/null || true
  while true; do
    echo
    c 1; echo "Settings"; c 0
    echo "  1) Memory for Windows      : ${RAM:-6G}"
    echo "  2) CPU cores               : ${CORES:-4}"
    echo "  3) Disk size (applies to a NEW Windows only): ${DISK:-40G}"
    echo "  4) Record the attached device's USB messages to a local file (troubleshooting): $([[ "${RESEARCH:-0}" == 1 ]] && echo on || echo off)"
    echo "  b) Back"
    ask "  Choose" "b"
    case "$REPLY" in
      1) ask "  GB (3 to 10)" "6"; [[ "$REPLY" =~ ^[0-9]+$ && "$REPLY" -ge 3 && "$REPLY" -le 10 ]] && { save_conf RAM "${REPLY}G"; RAM="${REPLY}G"; } || say "  Not changed.";;
      2) ask "  Cores (1 to 8)" "4"; [[ "$REPLY" =~ ^[0-9]+$ && "$REPLY" -ge 1 && "$REPLY" -le 8 ]] && { save_conf CORES "$REPLY"; CORES="$REPLY"; } || say "  Not changed.";;
      3) ask "  GB (30 to 256)" "40"; [[ "$REPLY" =~ ^[0-9]+$ && "$REPLY" -ge 30 && "$REPLY" -le 256 ]] && { save_conf DISK "${REPLY}G"; DISK="${REPLY}G"; } || say "  Not changed.";;
      4) if [[ "${RESEARCH:-0}" == 1 ]]; then save_conf RESEARCH 0; RESEARCH=0; else save_conf RESEARCH 1; RESEARCH=1; fi;;
      b|B|"") return 0;;
      *) say "  Please choose a number from the list.";;
    esac
  done
}

# ----------------------------------------------------------------- cleanup ----
cmd_cleanup() {
  while true; do
    load_state
    echo
    c 1; echo "Clean up"; c 0
    echo "  1) Reset Windows only       (deletes the Windows disk, about $(dir_size "$STORAGE") now; the program is kept)"
    echo "  2) Remove the downloaded VM software (about $(dir_size "$PODROOT_U" "$PODROOT"); re-downloaded when needed)"
    echo "  3) Repair SteamOS (restore Xbox controller drivers and stop anything left running)"
    echo "  4) Remove EVERYTHING this tool created (Windows, software, shortcuts, logs)"
    echo "  b) Back"
    ask "  Choose" "b"
    case "$REPLY" in
      1) confirm "  Really delete your Windows? This cannot be undone." n && { graceful_stop_vm; bg_stop_all; rm_tree "$STORAGE"; clear_active; save_state INSTALLED 0; ok "Windows deleted."; };;
      2) confirm "  Remove the VM software?" y && { remove_vm_software; ok "Removed."; };;
      3) cmd_stop;;
      4) cmd_uninstall; return 0;;
      b|B|"") return 0;;
      *) say "  Please choose a number from the list.";;
    esac
  done
}

remove_vm_software() { # both stores; the administrator-mode one only if it exists (then the password is needed)
  graceful_stop_vm
  pm_u rmi -af >/dev/null 2>&1 || true
  rm_tree "$PODROOT_U" "$PODRUN_U"
  if [[ -e "$PODROOT" || -e "$PODRUN" ]]; then
    need_sudo "to remove the administrator-mode copy of the VM software"
    pm_r rmi -af >/dev/null 2>&1 || true
    "${SUDO[@]}" rm -rf "$PODROOT" "$PODRUN"
  fi
}

cmd_uninstall() {
  say
  say "  This will remove:"
  say "    - the Windows disk and the VM software in $BASE"
  say "    - the logs and settings in $BASE"
  say "    - the temporary Xbox driver block (if any), the desktop shortcut and the launcher"
  confirm "  Type y to remove everything" n || { say "  Cancelled."; return 0; }
  load_state
  root_traces && need_sudo "to undo the USB changes and remove administrator-mode files"
  graceful_stop_vm
  bg_stop_all
  if root_traces; then
    unblock_host_drivers
    local m
    for m in ${HOST_MODS_UNLOADED//,/ }; do "${SUDO[@]}" modprobe "$m" 2>/dev/null || true; done
  fi
  steam_shortcut_remove
  local keep="$HOME/deckvm-last-report.txt"
  ls -t "$BASE"/report-*.txt >/dev/null 2>&1 && cp "$(ls -t "$BASE"/report-*.txt | head -1)" "$keep" && say "  Kept your latest report at $keep"
  remove_vm_software
  NOLOG=1
  rm -rf "$HOME"/.var/app/*/config/deckvm-profile 2>/dev/null   # the window's own browser profile when the browser is a Flatpak
  rm_tree "$BASE"
  rm -f "$LAUNCHER" "$DESKTOP_FILE" "$APP_FILE"
  ok "Everything removed. Free space now: $(free_gb "$HOME") GB"
}

# --------------------------------------------------------------- shortcuts ----
cmd_shortcut() { # desktop shortcut + a "deckvm" command
  persist_self
  write_icon
  mkdir -p "$(dirname "$LAUNCHER")" "$HOME/Desktop"
  printf '#!/usr/bin/env bash\nexec bash %q "$@"\n' "$SELF" > "$LAUNCHER"; chmod +x "$LAUNCHER"
  cat > "$DESKTOP_FILE" <<EOF
[Desktop Entry]
Type=Application
Name=DeckVM
Comment=Run Windows on your Steam Deck
Exec=bash "$SELF" gui
Icon=$ICON_FILE
StartupWMClass=DeckVM
StartupNotify=false
Terminal=false
Categories=Utility;
EOF
  chmod +x "$DESKTOP_FILE"
  save_state DESKTOP_SHORTCUT 1
  ok "Desktop shortcut created: 'DeckVM'. You can also type: deckvm"
}

STEAM_TAG="DeckVM"
STEAM_NAME="Windows (DeckVM)"

steam_cef_ready() {
  timeout 8 curl -s http://localhost:8080/json >/dev/null 2>&1 || timeout 8 curl -s http://localhost:8081/json >/dev/null 2>&1
}

write_steam_py() {
  cat > "$BASE/steam_sync.py" <<'STEAMPY_EOF'
#!/usr/bin/env python3
"""Add or remove a non-Steam shortcut through Steam's own remote debugger (Gaming Mode library).

Same method DeckZap uses (SteamClient.Apps in the Steam UI), trimmed down: no artwork.
Usage:
  steam_sync.py install NAME EXE STARTDIR LAUNCHOPTS COLLECTION
  steam_sync.py remove  NAME EXE STARTDIR LAUNCHOPTS COLLECTION   (removes every shortcut in COLLECTION)
Prints one result word, for example SUCCESS_INSTALLED.
"""
import base64
import json
import os
import socket
import sys
import time
import urllib.request
from urllib.parse import urlparse


def wait_for_ui(ports=(8080, 8081), timeout=60):
    start = time.time()
    while time.time() - start < timeout:
        for port in ports:
            try:
                with urllib.request.urlopen(f"http://localhost:{port}/json", timeout=3) as res:
                    if res.status == 200:
                        targets = json.loads(res.read().decode())
                        ws = next((t["webSocketDebuggerUrl"] for t in targets if t.get("title") == "SharedJSContext"), None)
                        if ws:
                            return ws
            except Exception:
                pass
        time.sleep(1)
    return None


def recv_ws_message(sock):
    while True:
        header = b""
        while len(header) < 2:
            chunk = sock.recv(2 - len(header))
            if not chunk:
                return ""
            header += chunk
        opcode = header[0] & 0x0F
        length = header[1] & 0x7F
        if length == 126:
            ext = b""
            while len(ext) < 2:
                ext += sock.recv(2 - len(ext))
            length = int.from_bytes(ext, "big")
        elif length == 127:
            ext = b""
            while len(ext) < 8:
                ext += sock.recv(8 - len(ext))
            length = int.from_bytes(ext, "big")
        data = b""
        while len(data) < length:
            chunk = sock.recv(length - len(data))
            if not chunk:
                break
            data += chunk
        if opcode == 0x9:
            sock.send(bytearray([0x8A, 0x00]))
            continue
        if opcode == 0x8:
            return ""
        if opcode == 0x1:
            return data.decode("utf-8", errors="ignore")


JS = r"""
(async () => {
  try {
    const MODE = __MODE__, NAME = __NAME__, EXE = __EXE__, DIR = __DIR__, OPTS = __OPTS__, TAG = __TAG__;
    let retries = 20;
    const getStore = () => window.g_CollectionStore || window.collectionStore;
    const getApps = () => window.SteamClient && window.SteamClient.Apps;
    while ((!getStore() || !getApps()) && retries > 0) { await new Promise(r => setTimeout(r, 500)); retries--; }
    const cStore = getStore(), cApps = getApps();
    if (!cStore || !cApps) return "FAIL_NO_API_HYDRATION";
    if (MODE === "install") {
      const appId = await cApps.AddShortcut(NAME, EXE, DIR, OPTS);
      await cApps.SetShortcutName(appId, NAME);
      await cApps.SetShortcutExe(appId, EXE);
      await cApps.SetShortcutStartDir(appId, DIR);
      await cApps.SetAppLaunchOptions(appId, OPTS);
      let col = null;
      if (typeof cStore.GetCollectionIDByUserTag === 'function') {
        const existing = cStore.GetCollectionIDByUserTag(TAG);
        if (existing) col = cStore.GetCollection(existing);
      }
      if (!col && typeof cStore.NewUnsavedCollection === 'function') col = cStore.NewUnsavedCollection(TAG, undefined, []);
      if (col) {
        if (col.Save) await col.Save();
        if (col.m_setApps && !col.m_setApps.has(appId)) {
          col.m_setApps.add(appId);
          if (col.m_setAddedManually) col.m_setAddedManually.add(appId);
          if (col.Save) await col.Save();
        }
        return "SUCCESS_INSTALLED";
      }
      return "FAIL_COLLECTION";
    }
    let removed = false;
    if (typeof cStore.GetCollectionIDByUserTag === 'function') {
      const existing = cStore.GetCollectionIDByUserTag(TAG);
      if (existing) {
        const col = cStore.GetCollection(existing);
        if (col && col.m_setApps) {
          for (const id of Array.from(col.m_setApps)) {
            if (typeof cApps.RemoveShortcut === 'function') { await cApps.RemoveShortcut(id); removed = true; }
          }
        }
      }
    }
    return removed ? "SUCCESS_REMOVED" : "SUCCESS_NOT_FOUND";
  } catch (e) { return "ERROR_" + e.message; }
})();
"""


def run(mode, name, exe, startdir, opts, tag):
    ws_url = wait_for_ui()
    if not ws_url:
        return "FAIL_NO_DEBUGGER_PORT"
    js = JS
    for key, val in (("__MODE__", mode), ("__NAME__", name), ("__EXE__", exe), ("__DIR__", startdir), ("__OPTS__", opts), ("__TAG__", tag)):
        js = js.replace(key, json.dumps(val))
    try:
        p = urlparse(ws_url)
        sock = socket.create_connection((p.hostname, p.port), timeout=10)
        key = base64.b64encode(os.urandom(16)).decode()
        sock.send((f"GET {p.path} HTTP/1.1\r\nHost: {p.hostname}:{p.port}\r\nUpgrade: websocket\r\n"
                   f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
        resp = b""
        while b"\r\n\r\n" not in resp and len(resp) < 8192:
            resp += sock.recv(1024)
        sock.settimeout(45)
        msg = json.dumps({"id": 1, "method": "Runtime.evaluate",
                          "params": {"expression": js, "awaitPromise": True, "returnByValue": True}}).encode()
        frame = bytearray([0x81])
        n = len(msg)
        if n <= 125:
            frame.append(n | 0x80)
        elif n <= 65535:
            frame.append(126 | 0x80)
            frame.extend(n.to_bytes(2, "big"))
        else:
            frame.append(127 | 0x80)
            frame.extend(n.to_bytes(8, "big"))
        mask = os.urandom(4)
        frame.extend(mask)
        frame.extend(bytearray(b ^ mask[i % 4] for i, b in enumerate(msg)))
        sock.send(frame)
        raw = recv_ws_message(sock)
        sock.close()
        try:
            return json.loads(raw)["result"]["result"]["value"]
        except Exception:
            return "FAIL_BAD_REPLY " + raw[:120]
    except Exception as exc:
        return f"FAIL_SOCKET_ERROR_{exc}"


if __name__ == "__main__":
    if len(sys.argv) != 7:
        print("usage: steam_sync.py install|remove NAME EXE STARTDIR LAUNCHOPTS COLLECTION")
        sys.exit(2)
    print(run(*sys.argv[1:]))
STEAMPY_EOF
}

# Adds a non-Steam shortcut (Gaming Mode) using Steam's own remote debugger, the same method DeckZap uses.
# The shortcut opens this tool's menu in Konsole; in Gaming Mode type your password with Steam+X (on-screen keyboard).
steam_shortcut() {
  step "Adding a shortcut to Steam (Gaming Mode)"
  persist_self
  if ! pgrep -x steam >/dev/null; then warn "Steam is not running, so I could not add the shortcut. Open Steam, then run: bash \"$SELF\" --shortcuts-only --steam-shortcut"; return 1; fi
  if ! steam_cef_ready; then
    mkdir -p "$HOME/.steam/steam"; touch "$HOME/.steam/steam/.cef-enable-remote-debugging"
    warn "One-time setup: Steam must be restarted so I can add the shortcut."
    say "  1. Exit Steam (taskbar icon, bottom right, then Quit) and open it again."
    say "  2. Run this to finish the shortcut:  bash \"$SELF\" --shortcuts-only --steam-shortcut"
    return 1
  fi
  write_steam_py
  local res
  res="$(python3 "$BASE/steam_sync.py" install "$STEAM_NAME" "/usr/bin/konsole" "/usr/bin" "--hold -e bash \"$SELF\"" "$STEAM_TAG" 2>&1 | tail -n 1)"
  dbg "steam shortcut result: $res"
  if [[ "$res" == SUCCESS_* ]]; then
    save_state STEAM_SHORTCUT 1
    ok "Steam shortcut added: Library > Collections > $STEAM_TAG. It has no artwork yet."
  else
    warn "Steam did not accept the shortcut ($res). The desktop shortcut still works."
    return 1
  fi
}
steam_shortcut_remove() {
  [[ "${STEAM_SHORTCUT:-0}" == 1 ]] || return 0
  if pgrep -x steam >/dev/null && steam_cef_ready; then
    write_steam_py
    python3 "$BASE/steam_sync.py" remove "$STEAM_NAME" "" "" "" "$STEAM_TAG" >/dev/null 2>&1 && ok "Steam shortcut removed." || warn "Could not remove the Steam shortcut: remove '$STEAM_NAME' in your Steam library (Options, Manage, Remove non-Steam game)."
  else
    warn "Steam is not ready, so the Steam shortcut stays. Remove '$STEAM_NAME' in your library (Options, Manage, Remove non-Steam game)."
  fi
}

cmd_note() {
  [[ $# -gt 0 ]] || { say 'usage: bash deckvm.sh note "what you saw"'; return 1; }
  event "NOTE" "$*"; ok "Noted."
}

# ------------------------------------------------------------------ report ----
redact() {
  local pw; pw="${WIN_PASS:-__none__}"
  [[ "$pw" == nerdzap || "$pw" == "$DEFAULT_WIN" ]] && pw="__none__"   # the simple default is not a secret, and redacting it would blank every "deckvm" in a report
  pw="$(printf '%s' "$pw" | sed 's/[][\/.*^$&|(){}+?]/\\&/g')"
  sed -E \
    -e "s/${pw}/***PASSWORD***/g" \
    -e 's/([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}/XX:XX:XX:XX:XX:XX/g' \
    -e 's/(PASSWORD=)[^ ]*/\1***/g'
}
section() { local title="$1"; shift; echo; echo "=================== $title ==================="; "$@" 2>&1 | redact; }
tailf() { [[ -f "$1" ]] && tail -n "${2:-150}" "$1" || echo "(no $1)"; }

rep_system()  { ( . /etc/os-release; echo "${PRETTY_NAME:-?} build=${BUILD_ID:-?}" ); uname -a; echo "model: $(cat /sys/class/dmi/id/product_name 2>/dev/null)"; grep -E 'MemTotal|MemAvailable' /proc/meminfo; df -h /home /var; }
rep_touch() {
  echo "enabled=$(touch_on && echo 1 || echo 0) image=$GUACD_IMAGE rdp_port=$RDP_PORT guacd_port=$GUACD_PORT published_last_start=${RDP_PUBLISHED:-?}"
  echo "-- listening:"; ss -tln 2>/dev/null | grep -E ":($RDP_PORT|$GUACD_PORT) " || echo "(nothing on those ports)"
  echo "-- helper container:"; pmg ps -a --filter "name=$GUACD_NAME" --format '{{.Names}} {{.Status}} {{.Image}}' 2>&1 | head -3
  echo "-- guacd.log (last 40):"; tail -n 40 "$LOGS/guacd.log" 2>/dev/null || echo "(none)"
  echo "-- helper container log (last 40):"; pmg logs --tail 40 "$GUACD_NAME" 2>&1 | head -50
  echo "-- window tunnel (gui.log lines):"; grep -i -E 'tunnel|rdp' "$LOGS/gui.log" 2>/dev/null | tail -n 30
}
rep_load() { # who is using the processor right now (press Make a report while Windows is slow)
  uptime 2>/dev/null
  local f; for f in cpu memory io; do [[ -r /proc/pressure/$f ]] && { printf 'pressure %s: ' "$f"; head -n 1 /proc/pressure/$f; }; done
  top -b -n 2 -d 1 -w 200 -o %CPU 2>/dev/null | awk '/^top -/{buf=""} {buf=buf $0 "\n"} END{printf "%s", buf}' | head -n 18
  echo "busiest threads:"; ps -eLo pid,tid,pcpu,comm --sort=-pcpu 2>/dev/null | head -n 8
}
rep_modules() { lsmod | grep -E '^(xpad|xbox_gip|usbmon|kvm|kvm_amd)'; ls -l /dev/kvm; echo "modprobe.d:"; ls -l /run/modprobe.d "$MODCONF_ETC" "$MODCONF_RUN" 2>/dev/null; }
rep_tools() {
  echo "image: $IMAGE"
  echo "image digest (normal-user store): $(podman --root "$PODROOT_U" --runroot "$PODRUN_U" image inspect "$IMAGE" --format '{{.Digest}} created {{.Created}}' 2>/dev/null || echo unknown)"
  echo "podman: $(podman --version 2>/dev/null)  rootless store backend: $(pm_u info --format '{{.Store.GraphDriverName}}' 2>/dev/null || echo ?)"
  echo "sudo: $(sudo -V 2>/dev/null | head -n 1)"
  echo "python: $(python3 --version 2>&1)   boot id: $BOOT_ID"
  echo "subuid: $(grep -E "^($(id -un)|$(id -u)):" /etc/subuid 2>/dev/null | head -n 1)   subgid: $(grep -E "^($(id -un)|$(id -u)):" /etc/subgid 2>/dev/null | head -n 1)"
  local b; for b in chromium chromium-browser google-chrome-stable google-chrome brave-browser microsoft-edge-stable kdialog zenity systemd-inhibit; do command -v "$b" >/dev/null 2>&1 && printf 'found: %s\n' "$b"; done
  flatpak list --app --columns=application 2>/dev/null | grep -Ei 'chrom|brave|edge' | sed 's/^/flatpak: /'
}
rep_podman()  {
  podman --version
  echo "base engine: $BASE_ENGINE   active engine: ${ACTIVE_ENGINE:-none}   rootless allowed: ${ROOTLESS:-?}"
  local ENGINE e
  for e in user root; do
    ENGINE=$e
    [[ $e == root && $EUID -ne 0 ]] && ! sudo -n true 2>/dev/null && { rep_rootinfo; continue; }
    echo "--- $e engine"
    pm info --format '{{.Host.OCIRuntime.Name}} cgroups={{.Host.CgroupsVersion}} driver={{.Store.GraphDriverName}} root={{.Store.GraphRoot}}'; pm images
  done
}
rep_rootinfo() { # administrator-mode details through the session helper (no password needed)
  if [[ "${ACTIVE_ENGINE:-}" == root ]] && wd_request rootinfo 20 >/dev/null; then
    echo "--- root engine (read by DeckVM's session helper)"
    awk '/ROOTINFO\|BEGIN/ {b=1; buf=""; next} /ROOTINFO\|END/ {last=buf; b=0; next} b {sub(/^.*ROOTINFO\|/, ""); buf=buf $0 "\n"} END {printf "%s", last}' "$LOGS/watchdog.log"
  else
    echo "--- root engine: not checked (no administrator access right now)"
  fi
}
rep_container() {
  local ENGINE e
  for e in user root; do
    ENGINE=$e
    [[ $e == root && $EUID -ne 0 ]] && ! sudo -n true 2>/dev/null && continue
    echo "--- $e engine"
    rep_container_one
  done
}
rep_container_one() {
  pm ps -a
  pm inspect -f 'status={{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}} pid={{.State.Pid}} started={{.State.StartedAt}} finished={{.State.FinishedAt}} error={{.State.Error}}' "$NAME"
  pm inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$NAME" | grep -E '^(VERSION|RAM_SIZE|CPU_CORES|DISK_SIZE|ARGUMENTS|NETWORK|LOG|GPU|REGION|KEYBOARD)='
}
rep_usb()     { command -v lsusb >/dev/null && lsusb -t; echo; echo "External devices now:"; list_usb; local p; p="$(list_usb | sed -n 1p | cut -d' ' -f1)"; [[ -n "$p" ]] && echo "Host driver(s) bound to $p: $(host_driver_of "$p")"; }
rep_kernel()  { grep -i -E 'usb|xpad|045e|kvm|oom|xbox' "$LOGS/kernel.log" 2>/dev/null | tail -n 150; }
rep_chead()   { head -n 60 "$LOGS/container.log" 2>/dev/null || echo "(no container.log)"; }
rep_shared()  { ls -laR "$SHARED" 2>/dev/null | head -n 80; }
rep_installlog() { if [[ -f "$SHARED/nerdzap-install.log" ]]; then tail -n 80 "$SHARED/nerdzap-install.log"; else echo "(no nerdzap-install.log)"; fi; }
rep_usbport() { # what the Deck's USB port can do (is there any way to cut a device's power from software?)
  local p; p="${PORT:-$(list_usb | sed -n 1p | cut -d' ' -f1)}"
  [[ -n "$p" ]] || { echo "(no device)"; return; }
  echo "port $p"; ls "$SYSFS/$p/port/" 2>/dev/null | tr '\n' ' '; echo
  local f; for f in connect_type disable early_stop location over_current_count; do [[ -r "$SYSFS/$p/port/$f" ]] && echo "$f=$(cat "$SYSFS/$p/port/$f" 2>/dev/null)"; done
  command -v lsusb >/dev/null && lsusb -v -s "${p%%-*}:1" 2>/dev/null | grep -iE 'wHubCharacteristics|power switching|per-port' | head -n 4
}
rep_capture() {
  local f; f="$(ls -lh "$LOGS"/*.pcap "$LOGS"/usbmon-bus*.txt "$LOGS"/usbcap.log 2>/dev/null)"
  if [[ -n "$f" ]]; then printf '%s\n' "$f"; else echo "no USB capture files in the logs folder (USB recording was off, or nothing has been recorded yet)"; fi
}
rep_bt()      { bluetoothctl --version 2>&1; bluetoothctl show 2>&1 | grep -E 'Powered|Pairable|Discoverable'; journalctl -u bluetooth --no-pager -n 40 -o short-iso 2>&1; }

cmd_report() {
  load_conf 2>/dev/null || true; load_state
  if [[ "${ACTIVE_ENGINE:-}" == root || "$BASE_ENGINE" == root ]] && ! sudo -n true 2>/dev/null && ! wd_alive; then
    need_sudo_quiet || warn "No administrator access: administrator-mode container details will be missing."
  fi
  local out; out="$BASE/report-$(date +%Y%m%d-%H%M%S).txt"
  step "Making a report"
  {
    echo "NerdZap DeckVM report"
    echo "generated: $(ts)   version: $TOOL_VERSION   image: $IMAGE"
    echo "settings: edition=${WIN_VERSION:-?} disk=${DISK:-?} ram=${RAM:-?} cores=${CORES:-?} research=${RESEARCH:-0} exp_gpu=${EXP_GPU:-0} extra_env=[${EXTRA_ENV:-}] extra_podman=[${EXTRA_PODMAN:-}] extra_qemu=[${EXTRA_QEMU:-}] session=[$(tr "\n" " " < "$SESSION_INFO" 2>/dev/null)] installed=${INSTALLED:-0}"
    section "TIMELINE (events.log)" cat "$EVENTS"
    section "SYSTEM" rep_system
    section "LOAD right now" rep_load
    section "TOUCH DISPLAY (guacd)" rep_touch
    section "MODULES / KVM" rep_modules
    section "PODMAN" rep_podman
    section "CONTAINER STATE" rep_container
    section "USB tree + external devices now" rep_usb
    section "USB timeline (changes seen during the session)" tailf "$LOGS/usb-timeline.log" 250
    section "WATCHDOG log" tailf "$LOGS/watchdog.log" 120
    section "RELAY log" tailf "$LOGS/relay.log" 120
    section "USB REDIRECTOR log" tailf "$LOGS/redir.log" 120
    section "USB REDIRECTOR output (usbredirect)" tailf "$LOGS/redir-${USBDEV_ID}.out" 60
    section "HOST kernel messages about USB/KVM/OOM" rep_kernel
    section "WINDOWS CONTAINER log: first 60 lines" rep_chead
    section "WINDOWS CONTAINER log: last 120 lines" tailf "$LOGS/container.log" 120
    section "SHARED folder (Z: in Windows)" rep_shared
    section "nerdzap-install.log (what Windows' first-logon step did)" rep_installlog
    section "USB port details" rep_usbport
    section "USB capture files" rep_capture
    section "BLUETOOTH (addresses redacted)" rep_bt
    section "DETAIL log (last 250 lines)" tailf "$LOGS/detail.log" 250
    section "COMMANDS log (last 120 lines)" tailf "$LOGS/commands.log" 120
    section "WINDOW (gui.log, last 80 lines)" tailf "$LOGS/gui.log" 80
    section "SESSION log (last 80 lines)" tailf "$LOGS/session.log" 80
    section "JOBS log (what each window job printed, last 200 lines)" tailf "$LOGS/jobs.log" 200
    section "TOOLS and VERSIONS" rep_tools
  } > "$out" 2>&1
  chmod 600 "$out"
  ok "Report written: $out ($(du -h "$out" | cut -f1))"
  say "  Passwords and Bluetooth addresses are masked. Send me this file, and tell me what you saw on screen."
  [[ "${RESEARCH:-0}" == 1 ]] && say "  USB recording was on: the recording (.pcap) is in $LOGS. It only contains the attached device. Send it only if you want to."
}

cmd_logs() { say "  Windows log (Ctrl+C to leave)"; tail -n 40 -f "$LOGS/container.log" 2>/dev/null || { ENGINE="${ACTIVE_ENGINE:-$ENGINE}"; pm logs -f "$NAME"; }; }

# -------------------------------------------------------------------- menu ----
cmd_help() {
  cat <<EOF
NerdZap DeckVM $TOOL_VERSION

Normal use: generate your command on nerdzap.com, paste it in Konsole.
Windows runs in normal user mode and needs no password. Only handing a USB device to Windows asks for it.

  bash deckvm.sh                 open the menu
  bash deckvm.sh gui             open the DeckVM window (Windows plus all the tools, in one place)
  bash deckvm.sh setup|start|xbox|usb|stop|status|settings|cleanup|report|logs|shortcut
  bash deckvm.sh selftest [quick|lifecycle|full|usb|all]   check DeckVM on this Deck and write a report (full deletes Windows: add --yes-delete)

One-line options (what the website generates):
  --win CODE        11 | 11l | tiny11 | core11 | 10 | 10l | tiny10   (default 11)
  --ram N           GB of memory for Windows (3 to 10, default 6)
  --disk N          GB for the Windows disk (30 to 256, default 40)
  --cores N         CPU cores (1 to 8, default 4)
  --xbox            then run the guided Xbox controller firmware update
  --start           then start Windows
  --desktop-shortcut  add a desktop shortcut
  --steam-shortcut    add a Gaming Mode (Steam) shortcut
  --record-usb      record the attached device's USB messages to a local file in the logs folder (troubleshooting)
                    (--research is the older name and still works)
  --cli             stay in this terminal instead of opening the DeckVM window
Cleanup:
  --reset-windows   delete the Windows disk only
  --remove-all      remove everything this tool created
Logs: $LOGS
EOF
}

cmd_menu() {
  while true; do
    load_conf 2>/dev/null || true; load_state
    echo
    c 1; echo "================  NerdZap DeckVM  v$TOOL_VERSION  ================"; c 0
    if installed; then echo "  Windows: $(edition_name "$WIN_VERSION") installed, $(vm_state 2>/dev/null || echo ?)"; else echo "  Windows: not set up yet"; fi
    echo
    echo "   1) Set up Windows"
    echo "   2) Start Windows"
    echo "   3) Update an Xbox controller's firmware (guided, asks for your password)"
    echo "   4) Start Windows with a USB device attached (asks for your password)"
    echo "   5) Stop Windows"
    echo "   6) Settings"
    echo "   7) Clean up / uninstall"
    echo "   8) Make a report for NerdZap (if something went wrong)"
    echo "   9) Create a desktop shortcut"
    echo "  10) Add a Steam shortcut (Gaming Mode)"
    echo "   q) Quit"
    ask "  Choose" ""
    case "$REPLY" in
      1) ( cmd_setup );;
      2) ( cmd_start );;
      3) ( cmd_xbox );;
      4) ( cmd_usb );;
      5) ( cmd_stop );;
      6) cmd_settings;;
      7) cmd_cleanup;;
      8) ( cmd_report );;
      9) ( cmd_shortcut );;
      10) ( steam_shortcut );;
      q|Q) exit 0;;
      *) say "  Please type a number from the list.";;
    esac
  done
}

# -------------------------------------------------------------------- gui ----
ICON_FILE="$BASE/deckvm-icon.png"
write_icon() { # the DeckVM app icon (navy tile, white and orange DVM), for the desktop shortcut and the window
  mkdir -p "$BASE"
  printf '%s' 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAtbElEQVR42u2deZxcZZX3v+e5t5auXrIDAQQX9l0Ie0BFJIAiMqKAAQKoIzKu8xlGRn3dxgXReWd0xhFfIYEQwr7JImERAoQ9hC2sCUvAhGzdSXe6qrrq3ud5/7hVTSXpJN1dt6qrO+f7+RR8aLqr+9665/ecc57znCM0Lqb0sqVXBTunE5ns7tbxEc+5fZ3Qgsih4AwwFtgTRYmfl4F2EItzT4hjXSjyghEWF7OZV+HtfP+f4cZAGvDvMYBb74a1TBzv2eBAwR0uIgc5yx4ibkeQdN/X4PRRVeplLg5c3jl5VwyvOOfmO+Sx0PjPsG7Zqg3EQErPtVMB6Fspg/IXki3j9rAhH0Nkijh3NMaMW9++e/9hN7gWaUBhU0YGrsJ43fqGLes/ddaudiIP4dwc4zG3sG71KxX/128Ur2CoDcUr/TsEoHnbbRIuPMnBiQLHIdIS3epeYw8rvATU0JUGEgYqVncPEKT0eDq3zsE9AncVxbud7uU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OnBqW8NnrPnqwNsrd7icxShxwuYlpK5we0aEhRtrzqW8R4DlYJ7jtBbtVPoSc/0CKfoRCAyl0AY4vZ+X4qfYeDXUTMruCkpF4qBIrSl7sPHmKMw84xxp5e7F49p8J7tvFPC63tBXlhIbfCFrOzTLJpDcIBIqatJAQaFijK+924DWKME/ceuB8G3au+GRZyq/p7qq8RBaByJpnYYvbxpDfqBottE2EfRBIVqqcegbK1rvhSarxbcI4rfJs4q5BbcU/Zbmp94E7qOpu8FL8kMhMOcOIuFmRKdCscpdDAUyFQthLD90szOHG4OeLkomJ25bMb2gr1mBpCfaeU9A4b8TITjhPnpopwGiKpkhCElSPL9XlRRkxir2zcIuBcj3Nc50SuDrMr76kwfFvPrXMZsmGFFWeWE5kJ+1trzxXPfEGQ7cGhYqCMOKNHcLilLrQ3GGNmFLMrn6scyTcU/TWG2qi8iiQING+7TcKFJzk4UeA4RFoqQoTKfIHR04dKgxk7Fau3V4rtS//XrXNwj8BdRfFup3v5ij6ff4ZocCCNML44evUWOCRbxu1hQz6GyBRx7miMGbf+7XYbqqxsoKaKUqMGHOsZfck7lfWfOmtXO5GHcG6O8ZhbWLf6FdYvnbeN0FGr0QxFKsKD929Oy8Txng0OFNzhInKQs+wh4nYESfd9DVp9rNTNXBy4vHPyrhhecc7Nd8hjofGfYd2yVRssclLvGH+4CUBfXkEfSrlzOpHJ7m4dH/Gc29cJLYgcCs4AY4E99WFVasDLQDuIxbknxLEuFHnBCIuL2cyr8Ha+/89wY/D/AVLkc1eYjX5nAAAAAElFTkSuQmCC' | base64 -d > "$ICON_FILE" 2>/dev/null || true
}

write_gui_py() {
  mkdir -p "$BASE"
  write_icon
  cat > "$GUI_PY" <<'GUIPY_EOF'
#!/usr/bin/env python3
# NerdZap DeckVM: the local window. Serves one page on 127.0.0.1 and runs the DeckVM script for it.
# Safety: listens on 127.0.0.1 only, needs a random token (set as a cookie from the shortcut's address),
# checks Host/Origin, and only ever runs a fixed list of DeckVM commands with validated values.
import base64, codecs, hashlib, uuid, http.server, socketserver, json, os, re, secrets, shlex, signal, socket, subprocess, sys, threading, time, urllib.parse, pty, select, fcntl, termios, struct

BASE = os.environ.get("DECKVM_BASE") or os.path.expanduser("~/deckvm")
SELF = os.path.join(BASE, "deckvm.sh")
LOGS = os.path.join(BASE, "logs")
INFO = os.path.join(BASE, "gui.json")
PENDING = os.path.join(BASE, "gui-pending.json")
UI_CONTINUE = os.path.join(BASE, "ui-continue")
UI_SKIP = os.path.join(BASE, "ui-skip-replug")
ASK_WAIT = os.path.join(BASE, "askpass.waiting")   # exists while the password window is on screen; holds what it is for
TOKEN = secrets.token_urlsafe(24)
EDITIONS = {"11", "11l", "tiny11", "core11", "10", "10l", "tiny10"}
ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07|\x1b[()][A-Z0-9]")
PORT = 0
RDP_PORT = int(os.environ.get("DECKVM_RDP_PORT") or 33890)     # Windows' remote desktop, published on 127.0.0.1 only (same numbers as in deckvm.sh)
GUACD_PORT = int(os.environ.get("DECKVM_GUACD_PORT") or 48220)   # the guacd helper container, 127.0.0.1 only

lock = threading.RLock()
STATUS = {}
STATUS_T = 0.0
LAST_POLL = time.monotonic()
JOB = None          # the current or last job
AFTER = None        # what the page should do when the first-run job ends ("xbox" or "start")


def log(m):
    print("[%s] %s" % (time.strftime("%H:%M:%S"), m), flush=True)


def clean(s):
    return ANSI.sub("", s).replace("\x00", "")


# ------------------------------------------------------------------ status ----
def run_script(args, timeout=30, extra_env=None):
    env = dict(os.environ, DECKVM_BASE=BASE, TERM="dumb")
    if extra_env:
        env.update(extra_env)
    try:
        r = subprocess.run(["bash", SELF] + args, capture_output=True, text=True, timeout=timeout, env=env, stdin=subprocess.DEVNULL)
        return r.stdout
    except Exception as e:  # noqa
        return ""


def parse_kv(text):
    d = {}
    for line in text.splitlines():
        if "=" in line:
            k, v = line.split("=", 1)
            d[k.strip()] = v.strip()
    return d


BUSY_FILE = os.path.join(BASE, "gui.busy")
RESUME = {"tried": False}


def write_busy_marker():
    """`bash deckvm.sh gui` reads this: a window server with a job running is never replaced by a newer one."""
    with lock:
        job = JOB if (JOB is not None and JOB.ended is None) else None
        name = job.name if job else ""
    try:
        if name:
            with open(BUSY_FILE, "w") as f:
                f.write(name)
        elif os.path.exists(BUSY_FILE):
            os.remove(BUSY_FILE)
    except OSError:
        pass


def last_start_offset():
    """Where the Windows log of the container that is running now begins (dockur's first line of every start)."""
    try:
        with open(os.path.join(LOGS, "container.log"), "rb") as f:
            data = f.read()
    except OSError:
        return 0
    i = data.rfind(b"Starting Windows for")
    return 0 if i < 0 else data.rfind(b"\n", 0, i) + 1


def adopt_running_setup():
    """Windows is installing in its container but no job here is watching it (the window server that started it was replaced,
    killed or restarted). Pick it up again so the page shows the progress and the setup finishes properly."""
    with lock:
        st = dict(STATUS)
        busy = JOB is not None and JOB.ended is None
    if st.get("vm") != "running":
        RESUME["tried"] = False
        return
    if busy or RESUME["tried"] or st.get("installed") != "0":
        return
    RESUME["tried"] = True
    try:
        job = start_job("auto", "Setting up Windows", [["resume"]])
        if job is not None:
            job.clog_offset = last_start_offset()
            log("picked up a Windows setup that was already running")
    except Exception as e:  # noqa
        log("could not pick up the running setup: %s" % e)


def status_loop():
    global STATUS, STATUS_T
    while True:
        write_busy_marker()
        out = run_script(["status-kv"], 25)
        d = parse_kv(out)
        if d:
            with lock:
                STATUS = d
                STATUS_T = time.time()
            adopt_running_setup()
        write_busy_marker()
        # Poll quickly while a window is open or something is happening; slowly when nobody is looking.
        with lock:
            busy = JOB is not None and JOB.ended is None
        time.sleep(1.5 if (busy or time.monotonic() - LAST_POLL < 60) else 15)


VHOST = ["localhost", -1000.0]


def view_host():
    """The name the Windows screen is opened under. "localhost" gets its own browser process (see the page); if that name does not reach
    the screen on this machine, fall back to 127.0.0.1. Only decided while the screen is up, then remembered for a minute."""
    now = time.monotonic()
    if now - VHOST[1] < 60:
        return VHOST[0]
    if not port_open(8006):
        return VHOST[0]
    try:
        with socket.create_connection(("localhost", 8006), timeout=1.0):
            VHOST[0] = "localhost"
    except OSError:
        VHOST[0] = "127.0.0.1"
    VHOST[1] = now
    return VHOST[0]


def port_open(port):
    try:
        with socket.create_connection(("127.0.0.1", port), timeout=0.5):
            return True
    except OSError:
        return False


# -------------------------------------------------------------------- jobs ----
class Job:
    def __init__(self, name, label):
        self.id = secrets.token_hex(4)
        self.name = name
        self.label = label
        self.started = time.time()
        self.ended = None
        self.rc = None
        self.lines = []
        self.pid = None
        self.cancelled = False
        self.storage0 = 0
        try:
            self.storage0 = storage_bytes()
        except Exception:  # noqa
            pass
        try:
            self.clog_offset = os.path.getsize(os.path.join(LOGS, "container.log"))
        except OSError:
            self.clog_offset = 0

    def summary(self):
        step = ""
        for ln in reversed(self.lines[-80:]):
            if ln.startswith("> "):
                step = ln[2:]
                break
        fails = [ln for ln in self.lines if "[FAIL]" in ln]
        return {"id": self.id, "name": self.name, "label": self.label, "running": self.ended is None,
                "rc": self.rc, "started": self.started, "ended": self.ended, "n": len(self.lines), "cancelled": self.cancelled,
                "step": step, "tail": self.lines[-60:], "fail": " ".join(dict.fromkeys(f.split("[FAIL]", 1)[1].strip() for f in fails))[:300],
                "single": any("designed to run a single Windows" in ln for ln in self.lines)}


def keep_job_log(job):
    """Appends what the job printed to jobs.log (kept between jobs, so the report can show what a stuck or cancelled job was doing)."""
    try:
        path = os.path.join(LOGS, "jobs.log")
        with lock:
            lines = list(job.lines[-150:])
        with open(path, "a", encoding="utf-8") as f:
            f.write("===== %s :: %s [%s] ended after %ds, rc=%s%s =====\n" % (
                time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(job.started)), job.label, job.name,
                (job.ended or time.time()) - job.started, job.rc, ", cancelled from the window" if job.cancelled else ""))
            for l in lines:
                f.write("  " + l + "\n")
        if os.path.getsize(path) > 300000:
            with open(path, "rb") as f:
                f.seek(-150000, 2)
                tail = f.read()
            with open(path, "wb") as f:
                f.write(tail[tail.find(b"\n") + 1:])
    except Exception:  # noqa
        pass


def reader(job, fd, pid):
    """Collect the job's output. The job is over when its bash exits. Helpers it leaves running (USB watchers started
    through sudo keep the pseudo-terminal open) must not keep the window waiting forever."""
    buf = b""
    rc = None

    def feed(data):
        nonlocal buf
        buf += data
        parts = re.split(rb"\r\n|\n|\r", buf)
        buf = parts.pop()
        with lock:
            for p in parts:
                t = clean(p.decode("utf-8", "replace")).rstrip()
                if t:
                    job.lines.append(t)
            if len(job.lines) > 6000:
                del job.lines[:1000]

    while True:
        try:
            r, _, _ = select.select([fd], [], [], 0.5)
            if r:
                data = os.read(fd, 4096)
                if not data:
                    break
                feed(data)
                continue
        except OSError:
            break
        try:
            done, status = os.waitpid(pid, os.WNOHANG)
        except OSError:
            done, status = pid, 0
        if done:
            rc = os.waitstatus_to_exitcode(status)
            for _ in range(20):  # whatever it printed last
                try:
                    r, _, _ = select.select([fd], [], [], 0.2)
                    if not r:
                        break
                    data = os.read(fd, 4096)
                    if not data:
                        break
                    feed(data)
                except OSError:
                    break
            break
    if buf:
        with lock:
            t = clean(buf.decode("utf-8", "replace")).rstrip()
            if t:
                job.lines.append(t)
    if rc is None:
        try:
            _, status = os.waitpid(pid, 0)
            rc = os.waitstatus_to_exitcode(status)
        except OSError:
            rc = -1
    with lock:
        job.rc = rc
        job.ended = time.time()
    keep_job_log(job)
    try:
        os.close(fd)
    except OSError:
        pass


def start_job(name, label, cmds, env_extra=None):
    """cmds: list of argv lists (each runs `bash deckvm.sh <argv>`), run one after another in a pseudo-terminal
    so that sudo's password ticket is shared by everything the job starts."""
    global JOB
    with lock:
        if JOB is not None and JOB.ended is None:
            return None
        job = Job(name, label)
        JOB = job
        if name == "auto":
            RESUME["tried"] = True
    del ARIA[:], SAMPLES[:], NETS[:]
    if name in ("auto", "setup"):          # the step left over from an earlier attempt must not show for the new one
        try:
            os.remove(os.path.join(BASE, "stage"))
        except OSError:
            pass
    AST.clear()
    if os.path.exists(UI_CONTINUE):
        try:
            os.remove(UI_CONTINUE)
        except OSError:
            pass
    shell = " && ".join("bash " + shlex.quote(SELF) + " " + " ".join(shlex.quote(a) for a in c) for c in cmds)
    env = dict(os.environ, DECKVM_GUI="1", DECKVM_NONINTERACTIVE="1", DECKVM_BASE=BASE, TERM="dumb")
    if env_extra:
        env.update(env_extra)
    pid, fd = pty.fork()
    if pid == 0:
        try:
            os.execvpe("bash", ["bash", "-c", shell], env)
        finally:
            os._exit(127)
    try:
        fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 50, 220, 0, 0))
    except OSError:
        pass
    job.pid = pid
    threading.Thread(target=reader, args=(job, fd, pid), daemon=True).start()
    return job


INT = lambda v, lo, hi: isinstance(v, (int, str)) and re.fullmatch(r"\d{1,3}", str(v)) and lo <= int(v) <= hi


def parse_auto_args(args):
    """Validate the flags the website's command carried. Returns (argv, after) or raises ValueError."""
    out, after, i = [], None, 0
    while i < len(args):
        a = args[i]
        if a in ("--win", "--ram", "--disk", "--cores"):
            v = args[i + 1] if i + 1 < len(args) else ""
            ok = (a == "--win" and v in EDITIONS) or (a == "--ram" and INT(v, 3, 10)) or (a == "--disk" and INT(v, 30, 256)) or (a == "--cores" and INT(v, 1, 8))
            if not ok:
                raise ValueError("bad value for " + a)
            out += [a, v]
            i += 2
            continue
        if a in ("--gpu", "--no-gpu", "--xbox-app", "--research", "--record-usb"):
            out.append(a)
        elif a == "--xbox":
            after = "xbox"
        elif a == "--start":
            after = after or "start"
        else:
            raise ValueError("unknown option")
        i += 1
    return out, after


def make_job(req):
    global AFTER
    n = req.get("name")
    if n == "setup":
        p = req.get("opts") or {}
        args = []
        if p.get("win") not in EDITIONS:
            raise ValueError("Choose a Windows version.")
        args += ["--win", p["win"]]
        for key, lo, hi in (("ram", 3, 10), ("disk", 30, 256), ("cores", 1, 8)):
            if p.get(key) is not None:
                if not INT(p[key], lo, hi):
                    raise ValueError("%s must be %d to %d" % (key, lo, hi))
                args += ["--" + key, str(p[key])]
        return start_job("auto", "Setting up Windows", [args])
    if n == "auto":
        args, after = parse_auto_args(req.get("args") or [])
        with lock:
            AFTER = after
        try:
            os.remove(PENDING)
        except OSError:
            pass
        return start_job("auto", "Setting up Windows", [args])
    if n == "start":
        return start_job("start", "Starting Windows", [["start"]])
    if n == "stop":
        return start_job("stop", "Stopping Windows", [["stop"]])
    if n in ("xbox", "usb"):
        ports = req.get("ports")
        if ports is None:
            ports = [req.get("port") or ""]
        if not isinstance(ports, list) or not ports or len(ports) > 4:
            raise ValueError("Choose a device first.")
        ports = list(dict.fromkeys(str(p) for p in ports))
        for port in ports:
            if not re.fullmatch(r"\d+-\d+(\.\d+)*", port):
                raise ValueError("Choose a device first.")
        label = "Starting the controller update session" if n == "xbox" else "Starting Windows with your device%s" % ("s" if len(ports) > 1 else "")
        return start_job(n, label, [[n]], {"DECKVM_USB_PORT": ",".join(ports)})
    if n == "reattach":
        return start_job("reattach", "Reconnecting the device", [["reattach"]])
    if n == "repair":
        return start_job("repair", "Putting SteamOS's controller drivers back", [["stop"]])
    if n == "eject":
        return start_job("eject", "Ejecting the install disc", [["eject"]])
    if n == "reset":
        return start_job("reset", "Deleting Windows", [["--reset-windows"]], {"DECKVM_YES": "1"})
    if n == "uninstall":
        return start_job("uninstall", "Removing DeckVM", [["--remove-all"]], {"DECKVM_YES": "1"})
    if n == "report":
        return start_job("report", "Making a report", [["report"]])
    if n == "settings":
        cmds = []
        p = req.get("opts") or {}
        for key, lo, hi in (("ram", 3, 10), ("cores", 1, 8), ("disk", 30, 256)):
            if p.get(key) is not None:
                if not INT(p[key], lo, hi):
                    raise ValueError("%s must be %d to %d" % (key, lo, hi))
                cmds.append(["set", key, str(p[key])])
        for key in ("research", "touch"):
            if key in p:
                cmds.append(["set", key, "1" if p[key] else "0"])
        for key in ("extra_env", "extra_podman", "extra_qemu"):
            if key in p:
                v = str(p[key]).strip()
                if len(v) > 300 or not re.fullmatch(r"[ -~]*", v):
                    raise ValueError("The advanced options may only use plain characters (300 at most).")
                cmds.append(["set", key, v])
        if not cmds:
            raise ValueError("Nothing to save.")
        return start_job("settings", "Saving settings", cmds)
    raise ValueError("Unknown action.")


# ------------------------------------------------------------------ cancel ----
CLEAN_FOR = {"auto": "auto", "setup": "auto", "start": "start", "xbox": "xbox", "usb": "usb", "stop": "stop"}


def cancel_job(keep):
    """Stop the running job and tidy up after it. Runs in the background; the page follows the new 'cancel' job."""
    with lock:
        job = JOB
        if job is None or job.ended is not None or job.name in ("cancel", "report"):
            return False
        if job.cancelled:
            return True   # a second press while the first is being carried out
        job.cancelled = True
        pid, name = job.pid, job.name

    def work():
        for sig, wait in ((signal.SIGTERM, 6.0), (signal.SIGKILL, 4.0)):
            try:
                os.killpg(pid, sig)
            except OSError:
                try:
                    os.kill(pid, sig)
                except OSError:
                    pass
            t0 = time.time()
            while time.time() - t0 < wait:
                if job.ended is not None:
                    break
                time.sleep(0.2)
            if job.ended is not None:
                break
        for _ in range(50):
            if job.ended is not None:
                break
            time.sleep(0.2)
        what = CLEAN_FOR.get(name)
        if what:
            start_job("cancel", "Cancelling", [["_cancelclean", what, "delete" if keep == "delete" else "keep"]])
    threading.Thread(target=work, daemon=True).start()
    return True


# ---------------------------------------------------------------- progress ----
ARIA = []
NETS = []      # (time, bytes received by this computer), to work out a live download speed
AST = {}       # smoothing state for the aria2 download figures
SAMPLES = []   # (time, bytes) of the storage folder, to work out a download speed


def storage_bytes():
    """Disk space really used by the Windows storage folder (sparse files count only what is written)."""
    total = 0
    root = os.path.join(BASE, "storage")
    for dp, dn, fn in os.walk(root):
        if dp[len(root):].count(os.sep) > 2:
            dn[:] = []
        for f in fn:
            try:
                total += os.lstat(os.path.join(dp, f)).st_blocks * 512
            except OSError:
                pass
    return total


def net_rx():
    """Bytes received so far by the Deck's real network connections (virtual interfaces are skipped)."""
    tot = 0
    try:
        with open("/proc/net/dev") as f:
            for ln in f.read().splitlines()[2:]:
                name, _, rest = ln.partition(":")
                name = name.strip()
                if not rest or name == "lo" or name.startswith(("veth", "cni", "podman", "docker", "virbr", "br-", "tap", "vnet")):
                    continue
                tot += int(rest.split()[0])
    except (OSError, ValueError, IndexError):
        return None
    return tot


def aria_figures(done, total):
    """aria2 only saves its control file every so often, so the pieces-done figure moves in big steps.
    Between steps, work out the speed from the network counters and carry the figure forward, so the screen moves smoothly."""
    now = time.monotonic()
    rx = net_rx()
    if rx is not None:
        NETS.append((now, rx))
    while len(NETS) > 1 and now - NETS[0][0] > 10:
        NETS.pop(0)
    inst = None
    if len(NETS) > 1 and NETS[-1][0] > NETS[0][0]:
        inst = max(0.0, (NETS[-1][1] - NETS[0][1]) / (NETS[-1][0] - NETS[0][0]))
    ARIA.append((now, done))
    while len(ARIA) > 1 and now - ARIA[0][0] > 90:
        ARIA.pop(0)
    if inst is None or inst < 50_000:   # no usable network figure: use the (steppy) disk figure over a longer window
        inst = None
        if len(ARIA) > 1 and ARIA[-1][1] > ARIA[0][1] and ARIA[-1][0] > ARIA[0][0]:
            inst = (ARIA[-1][1] - ARIA[0][1]) / (ARIA[-1][0] - ARIA[0][0])
    sp = AST.get("speed")
    if inst is not None:
        sp = inst if sp is None else sp * 0.7 + inst * 0.3
        AST["speed"], AST["t"] = sp, now
    elif sp is not None and now - AST.get("t", 0) > 20:
        sp = None
        AST.pop("speed", None)
    # carry the figure forward from the last time aria2's own figure changed
    if done != AST.get("done") or "base_rx" not in AST:
        AST["done"], AST["base_rx"] = done, rx
    shown = done
    if rx is not None and AST.get("base_rx") is not None and rx >= AST["base_rx"]:
        shown = max(done, min(int(total * 0.995), int(done + (rx - AST["base_rx"]) * 0.97)))
    shown = max(shown, AST.get("shown", 0))
    AST["shown"] = shown
    return shown, int(sp or 0)


def aria2_progress():
    """dockur downloads the ISO with aria2, which reserves the whole file up front (so disk use looks 'full' from the first second).
    The real progress is in the small control file next to it (name.iso.aria2): a bitmap of the pieces already downloaded."""
    root = os.path.join(BASE, "storage", "tmp")
    try:
        names = [n for n in os.listdir(root) if n.endswith(".aria2")]
    except OSError:
        return None
    for n in names:
        try:
            with open(os.path.join(root, n), "rb") as f:
                d = f.read(4 * 1024 * 1024)
            if len(d) < 34 or struct.unpack(">H", d[:2])[0] != 1:
                continue
            off = 6
            ihl = struct.unpack(">I", d[off:off + 4])[0]
            off += 4 + ihl
            piece = struct.unpack(">I", d[off:off + 4])[0]
            total = struct.unpack(">Q", d[off + 4:off + 12])[0]
            bflen = struct.unpack(">I", d[off + 20:off + 24])[0]
            bits = d[off + 24:off + 24 + bflen]
            npieces = -(-total // piece) if piece else 0
            if not piece or not total or len(bits) != bflen or bflen != -(-npieces // 8):
                continue
            have = sum(bin(b).count("1") for b in bits)
            done = min(total, have * piece)
            return {"done": done, "total": total, "file": n[:-6]}
        except (OSError, struct.error, ValueError):
            continue
    return None


def download_prepared():
    """True when an ISO is in the temp folder and aria2's control file is gone: the download has finished."""
    root = os.path.join(BASE, "storage", "tmp")
    try:
        files = os.listdir(root)
    except OSError:
        return False
    if any(n.endswith(".aria2") for n in files):
        return False
    return any(n.lower().endswith((".iso", ".esd", ".wim")) and os.path.getsize(os.path.join(root, n)) > 500_000_000 for n in files)


def download_stats(start_bytes):
    now = time.time()
    b = max(0, storage_bytes() - start_bytes)
    SAMPLES.append((now, b))
    while len(SAMPLES) > 1 and now - SAMPLES[0][0] > 12:
        SAMPLES.pop(0)
    speed = 0.0
    if len(SAMPLES) > 1 and SAMPLES[-1][0] > SAMPLES[0][0]:
        speed = max(0.0, (SAMPLES[-1][1] - SAMPLES[0][1]) / (SAMPLES[-1][0] - SAMPLES[0][0]))
    return b, speed


def pull_progress(job):
    """How far the VM software download is: the pull prints one 'Copying blob' line per part, again when it is done."""
    seen, done = {}, set()
    with lock:
        lines = list(job.lines[-1500:])
    for ln in lines:
        m = re.search(r"Copying blob (?:sha256:)?([0-9a-f]{6,})", ln)
        if m:
            seen[m.group(1)] = True
            if re.search(r"\bdone\b", ln):
                done.add(m.group(1))
    return {"parts": len(seen), "done": len(done)}


def container_progress(job):
    """What dockur is doing, read from the Windows log written since this job started."""
    path = os.path.join(LOGS, "container.log")
    res = {"phase": "", "pct": None, "downloading": "", "booted": False, "installing": False, "bytes": None, "speed": None}
    try:
        with open(path, "rb") as f:
            f.seek(job.clog_offset if job else 0)
            text = clean(f.read().decode("utf-8", "replace"))
    except OSError:
        return res
    lines = [ln.strip() for ln in re.split(r"[\r\n]+", text) if ln.strip()]
    for ln in lines:
        m = re.search(r"Downloading (.+?) from", ln)
        if m:
            res["downloading"] = m.group(1)
            res["pct"] = None
        pcts = re.findall(r"(\d{1,3})%", ln)
        if pcts and res["downloading"] and not res["booted"] and int(pcts[-1]) <= 100:
            res["pct"] = int(pcts[-1])
        if "Booting Windows" in ln or "Windows started successfully" in ln:
            res["booted"] = True
        if ln.startswith("❯"):
            res["phase"] = ln.lstrip("❯ ").strip()
    if res["booted"]:
        res["pct"] = None
    if res["downloading"] and not res["booted"] and job is not None:
        ar = aria2_progress()
        if ar:
            shown, sp = aria_figures(ar["done"], ar["total"])
            res["bytes"], res["speed"], res["total"] = int(shown), int(sp), int(ar["total"])
            res["pct"] = min(99, int(shown * 100 / ar["total"]))
        elif download_prepared():
            res["prep"] = True
        else:
            b, sp = download_stats(job.storage0)
            res["bytes"], res["speed"] = int(b), int(sp)
    return res


# -------------------------------------------------------- touch display ----
# The page shows Windows through Apache Guacamole's browser library. This server is the bridge: it opens a WebSocket
# for the page, does the Guacamole handshake with the guacd helper (so the Windows password never reaches the page),
# and then relays the two streams. Windows gets real touch events over RDP, which is what makes Windows show its
# touch keyboard.
TUNNELS = 0
RDP_CACHE = [0.0, False]
RDP_SINCE = [0.0]
WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
LAYOUTS = {"en_GB": "en-gb-qwerty", "en_US": "en-us-qwerty", "de_DE": "de-de-qwertz", "de_AT": "de-de-qwertz",
           "fr_FR": "fr-fr-azerty", "es_ES": "es-es-qwerty", "it_IT": "it-it-qwerty", "pt_BR": "pt-br-qwerty",
           "sv_SE": "sv-se-qwerty", "ja_JP": "ja-jp-qwerty", "da_DK": "da-dk-qwerty", "tr_TR": "tr-tr-qwerty"}


def conf_value(key, default=""):
    try:
        with open(os.path.join(BASE, "config.env")) as f:
            for ln in f:
                if ln.startswith(key + "="):
                    v = shlex.split(ln.split("=", 1)[1].strip())
                    return v[0] if v else default
    except (OSError, ValueError):
        pass
    return default


def rdp_ready():
    """True when Windows has answered on its remote desktop port for a while (a bare connection request; nothing logs in).
    The short wait keeps the display from logging in while Windows is still signing itself in at start-up."""
    now = time.monotonic()
    if now - RDP_CACHE[0] < 2.0:
        return RDP_CACHE[1]
    ok = False
    try:
        with socket.create_connection(("127.0.0.1", RDP_PORT), timeout=1.0) as s:
            s.settimeout(1.5)
            s.sendall(bytes([3, 0, 0, 19, 14, 0xE0, 0, 0, 0, 0, 0, 1, 0, 8, 0, 3, 0, 0, 0]))
            d = s.recv(4)
            ok = len(d) >= 4 and d[0] == 3
    except OSError:
        ok = False
    if not ok:
        RDP_SINCE[0] = 0.0
    elif not RDP_SINCE[0]:
        RDP_SINCE[0] = now
    ok = ok and now - RDP_SINCE[0] >= float(os.environ.get("DECKVM_RDP_SETTLE") or 20)
    RDP_CACHE[0], RDP_CACHE[1] = now, ok
    return ok


def g_enc(*els):
    return ",".join("%d.%s" % (len(e), e) for e in els) + ";"


def g_boundary(buf):
    """Index just after the last complete Guacamole instruction in buf (0 if none). Lengths count characters."""
    i, n, done = 0, len(buf), 0
    while i < n:
        j = buf.find(".", i)
        if j < 0:
            break
        try:
            ln = int(buf[i:j])
        except ValueError:
            raise ValueError("bad guacd stream")
        e = j + 1 + ln
        if e >= n:
            break
        c = buf[e]
        if c == ";":
            done = e + 1
            i = e + 1
        elif c == ",":
            i = e + 1
        else:
            raise ValueError("bad guacd stream")
    return done


def g_first(buf):
    """Parse the first complete instruction in buf: (list of elements, rest) or (None, buf)."""
    i, n, els = 0, len(buf), []
    while i < n:
        j = buf.find(".", i)
        if j < 0:
            break
        try:
            ln = int(buf[i:j])
        except ValueError:
            raise ValueError("bad guacd stream")
        e = j + 1 + ln
        if e >= n:
            break
        els.append(buf[j + 1:e])
        c = buf[e]
        if c == ";":
            return els, buf[e + 1:]
        if c != ",":
            raise ValueError("bad guacd stream")
        i = e + 1
    return None, buf


def ws_send(sock, wlock, opcode, payload):
    n = len(payload)
    h = bytearray([0x80 | opcode])
    if n < 126:
        h.append(n)
    elif n < 65536:
        h.append(126)
        h += struct.pack(">H", n)
    else:
        h.append(127)
        h += struct.pack(">Q", n)
    with wlock:
        sock.sendall(bytes(h) + payload)


def recv_exact(sock, n):
    chunks = []
    while n > 0:
        c = sock.recv(min(n, 65536))
        if not c:
            raise EOFError
        chunks.append(c)
        n -= len(c)
    return b"".join(chunks)


def ws_recv(sock):
    """One WebSocket message: (opcode, payload). Control frames are returned as they arrive."""
    msg, mop = b"", None
    while True:
        b1, b2 = recv_exact(sock, 2)
        fin, op, masked, n = b1 & 0x80, b1 & 0x0F, b2 & 0x80, b2 & 0x7F
        if n == 126:
            n = struct.unpack(">H", recv_exact(sock, 2))[0]
        elif n == 127:
            n = struct.unpack(">Q", recv_exact(sock, 8))[0]
        if n > (1 << 22):
            raise ValueError("frame too large")
        mask = recv_exact(sock, 4) if masked else None
        data = recv_exact(sock, n) if n else b""
        if mask and n:
            k = (mask * (n // 4 + 1))[:n]
            data = (int.from_bytes(data, "big") ^ int.from_bytes(k, "big")).to_bytes(n, "big")
        if op >= 8:
            return op, data
        if op != 0:
            mop = op
        msg += data
        if fin:
            return mop, msg


def guac_open(width, height, dpi, audio, image, tz, touch):
    """Connect to guacd and do the Guacamole handshake for an RDP session to the local Windows. Returns (socket, leftover)."""
    user = conf_value("WIN_USER", "nerdzap")
    pw = conf_value("WIN_PASS", "")
    lang = (os.environ.get("LC_ALL") or os.environ.get("LANG") or "")[:5]
    params = {
        "hostname": "127.0.0.1", "port": str(RDP_PORT), "username": user, "password": pw,
        "security": "any", "ignore-cert": "true", "enable-touch": "true" if touch else "false",
        "resize-method": "display-update", "color-depth": "24", "client-name": "DeckVM",
        "enable-wallpaper": "false", "enable-font-smoothing": "true", "enable-full-window-drag": "false",
        "enable-desktop-composition": "false", "enable-menu-animations": "false", "enable-theming": "true",
        "server-layout": LAYOUTS.get(lang, "failsafe"), "disable-audio": "false",
    }
    s = socket.create_connection(("127.0.0.1", GUACD_PORT), timeout=5)
    try:
        s.settimeout(20)
        s.sendall(g_enc("select", "rdp").encode())
        buf, dec, ins = "", codecs.getincrementaldecoder("utf-8")(errors="replace"), None
        while ins is None:
            d = s.recv(65536)
            if not d:
                raise OSError("guacd closed")
            buf += dec.decode(d)
            ins, buf = g_first(buf)
        if ins[0] != "args":
            raise OSError("guacd said " + ins[0])
        vals = [a if a.startswith("VERSION_") else params.get(a, "") for a in ins[1:]]
        out = g_enc("size", str(width), str(height), str(dpi)) + g_enc("audio", *audio) + g_enc("video") + g_enc("image", *image)
        if tz:
            out += g_enc("timezone", tz)
        out += g_enc("connect", *vals)
        s.sendall(out.encode())
        s.settimeout(None)
        return s, buf, dec
    except Exception:
        s.close()
        raise



# -------------------------------------------------------------------- http ----
class Handler(http.server.BaseHTTPRequestHandler):
    server_version = "DeckVM"
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *a):
        pass

    # --- helpers
    def host_ok(self):
        h = (self.headers.get("Host") or "").lower()
        return h in ("127.0.0.1:%d" % PORT, "localhost:%d" % PORT)

    def cookie_ok(self):
        for part in (self.headers.get("Cookie") or "").split(";"):
            k, _, v = part.strip().partition("=")
            if k == "deckvm" and secrets.compare_digest(v, TOKEN):
                return True
        return False

    def send(self, code, body, ctype="text/plain; charset=utf-8", extra=None):
        data = body if isinstance(body, bytes) else body.encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.send_header("Cache-Control", "no-store")
        self.send_header("X-Content-Type-Options", "nosniff")
        self.send_header("Content-Security-Policy",
                         "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; "
                         "frame-src http://127.0.0.1:8006 http://localhost:8006; "
                         "connect-src 'self' ws://127.0.0.1:%d ws://localhost:%d https://img.buymeacoffee.com; "
                         "img-src 'self' data: blob: https://img.buymeacoffee.com; media-src 'self' blob:" % (PORT, PORT))
        for k, v in (extra or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(data)

    def json(self, obj, code=200):
        self.send(code, json.dumps(obj), "application/json")

    def deny(self):
        self.send(403, "Open DeckVM from its desktop shortcut (or run: deckvm gui).")

    def tunnel(self, q):
        global TUNNELS
        o = self.headers.get("Origin", "")
        if o not in ("http://127.0.0.1:%d" % PORT, "http://localhost:%d" % PORT) or \
           "websocket" not in (self.headers.get("Upgrade") or "").lower() or not self.headers.get("Sec-WebSocket-Key"):
            return self.deny()

        def num(k, lo, hi, d):
            try:
                return max(lo, min(hi, int((q.get(k) or [d])[0])))
            except ValueError:
                return d
        w, h, dpi = num("w", 320, 4096, 1280), num("h", 240, 4096, 720), num("dpi", 48, 300, 96)
        audio = [a for a in (q.get("audio") or [""])[0].split(",") if re.fullmatch(r"audio/[A-Za-z0-9.+-]{1,20}", a)][:4]
        image = [a for a in (q.get("image") or ["image/png,image/jpeg"])[0].split(",") if re.fullmatch(r"image/[a-z0-9.+-]{1,12}", a)][:4]
        tz = (q.get("tz") or [""])[0]
        tz = tz if re.fullmatch(r"[A-Za-z0-9_+/-]{1,40}", tz) else ""
        touch = (q.get("touch") or ["1"])[0] != "0"
        with lock:
            if TUNNELS >= 3:
                return self.send(503, "busy")
            TUNNELS += 1
        g = None
        try:
            try:
                g, rest, dec = guac_open(w, h, dpi, audio, image or ["image/png"], tz, touch)
            except (OSError, ValueError) as e:
                log("tunnel: guacd handshake failed: %s" % e)
                return self.send(502, "The Windows display helper is not ready.")
            key = base64.b64encode(hashlib.sha1((self.headers["Sec-WebSocket-Key"] + WS_GUID).encode()).digest()).decode()
            self.send_response(101, "Switching Protocols")
            self.send_header("Upgrade", "websocket")
            self.send_header("Connection", "Upgrade")
            self.send_header("Sec-WebSocket-Accept", key)
            if "guacamole" in (self.headers.get("Sec-WebSocket-Protocol") or ""):
                self.send_header("Sec-WebSocket-Protocol", "guacamole")
            self.end_headers()
            self.wfile.flush()
            self.close_connection = True
            log("tunnel: open %dx%d dpi=%d touch=%s" % (w, h, dpi, touch))
            self.pipe(g, rest, dec)
        finally:
            if g:
                try:
                    g.close()
                except OSError:
                    pass
            with lock:
                TUNNELS -= 1
            log("tunnel: closed")

    def pipe(self, g, rest, dec):
        ws = self.connection
        ws.settimeout(None)
        wl = threading.Lock()

        def g2w():
            buf = rest
            try:
                ws_send(ws, wl, 1, g_enc("", uuid.uuid4().hex).encode())
                while True:
                    done = g_boundary(buf) if buf else 0
                    if done:
                        ws_send(ws, wl, 1, buf[:done].encode())
                        buf = buf[done:]
                        continue
                    d = g.recv(65536)
                    if not d:
                        break
                    buf += dec.decode(d)
            except (OSError, ValueError):
                pass
            try:
                ws_send(ws, wl, 8, struct.pack(">H", 1000))
                ws.shutdown(socket.SHUT_RDWR)
            except OSError:
                pass

        t = threading.Thread(target=g2w, daemon=True)
        t.start()
        try:
            while True:
                op, data = ws_recv(ws)
                if op == 8:
                    break
                if op == 9:
                    ws_send(ws, wl, 10, data)
                elif op in (1, 2):
                    if data.startswith(b"0.,"):            # the page's own keep-alive: answer it, do not pass it on
                        ws_send(ws, wl, 1, data)
                    else:
                        g.sendall(data)
        except (EOFError, OSError, ValueError):
            pass
        try:
            g.shutdown(socket.SHUT_RDWR)
        except OSError:
            pass
        t.join(2)

    # --- routes
    def do_GET(self):
        global LAST_POLL
        if not self.host_ok():
            return self.deny()
        u = urllib.parse.urlparse(self.path)
        q = urllib.parse.parse_qs(u.query)
        if u.path in ("/", "/samehost") and "t" in q:
            if secrets.compare_digest(q["t"][0], TOKEN):
                return self.send(302, "", extra={"Location": u.path, "Set-Cookie": "deckvm=%s; Path=/; HttpOnly; SameSite=Strict" % TOKEN})
            return self.deny()
        if u.path in ("/icon.png", "/favicon.ico"):   # the app icon is not secret; the browser asks for it without the token
            return self.send(200, ICON_PNG, "image/png")
        if not self.cookie_ok():
            return self.deny()
        if u.path == "/":
            return self.send(200, PAGE, "text/html; charset=utf-8")
        if u.path == "/samehost":   # for comparing browsers: the page with the Windows screen at 127.0.0.1, the same address as this page
            return self.send(200, PAGE.replace("<head>", "<head><script>window.SAMEHOST=1</script>", 1), "text/html; charset=utf-8")
        if u.path == "/guac.js":
            js = guac_js()
            if not js:
                return self.send(404, "not found")
            return self.send(200, js, "application/javascript; charset=utf-8")
        if u.path == "/tunnel":
            return self.tunnel(q)
        if u.path == "/api/state":
            LAST_POLL = time.monotonic()
            with lock:
                st = dict(STATUS)
                job = JOB
                js = job.summary() if job else None
                after = AFTER
            st["web"] = "1" if port_open(8006) else "0"
            st["vhost"] = view_host() if st["web"] == "1" else "localhost"
            st["rdp"] = "1" if (st.get("vm") == "running" and st.get("touch_session") == "1" and rdp_ready() and port_open(GUACD_PORT)) else "0"   # only probe when this session was started with the touch display
            st["ask"] = ""
            try:
                if job and job.ended is None and time.time() - os.path.getmtime(ASK_WAIT) < 600:
                    st["ask"] = open(ASK_WAIT).read().strip() or "for DeckVM"
            except OSError:
                pass
            pending = None
            if os.path.exists(PENDING):
                try:
                    pending = [ln.strip() for ln in open(PENDING).read().splitlines() if ln.strip()]
                except OSError:
                    pending = None
            prog = None
            if job and job.name in ("auto", "start", "xbox", "usb"):
                prog = container_progress(job)
                prog["pull"] = pull_progress(job)
            return self.json({"status": st, "job": js, "pending": pending, "after": after, "progress": prog,
                              "stage": st.get("stage", ""), "now": time.time()})
        if u.path == "/api/log":
            start = int((q.get("from") or ["0"])[0] or 0)
            with lock:
                job = JOB
                lines = job.lines[start:start + 800] if job else []
                nxt = start + len(lines)
                running = bool(job and job.ended is None)
            return self.json({"lines": lines, "next": nxt, "running": running, "id": job.id if job else None})
        if u.path == "/api/winlog":
            try:
                with open(os.path.join(LOGS, "container.log"), "rb") as f:
                    f.seek(0, 2)
                    size = f.tell()
                    f.seek(max(0, size - 24000))
                    text = clean(f.read().decode("utf-8", "replace"))
                lines = [ln for ln in text.splitlines() if ln.strip()][-200:]
            except OSError:
                lines = []
            return self.json({"lines": lines})
        if u.path == "/api/devices":
            devs = []
            for ln in run_script(["devices-kv"], 15).splitlines():
                if ln.startswith("dev="):
                    parts = ln[4:].split("|")
                    if len(parts) >= 4:
                        devs.append({"port": parts[0], "id": parts[1], "name": parts[2], "ms": parts[3] == "1",
                                     "internal": len(parts) > 4 and parts[4] == "1"})
            return self.json({"devices": devs})
        if u.path == "/api/report":
            try:
                files = sorted(f for f in os.listdir(BASE) if f.startswith("report-") and f.endswith(".txt"))
                if not files:
                    return self.json({"text": "", "path": ""})
                path = os.path.join(BASE, files[-1])
                with open(path, "rb") as f:
                    f.seek(0, 2)
                    size = f.tell()
                    f.seek(max(0, size - 400000))
                    return self.json({"text": f.read().decode("utf-8", "replace"), "path": path})
            except OSError:
                return self.json({"text": "", "path": ""})
        self.send(404, "Not found")

    def do_POST(self):
        if not self.host_ok() or not self.cookie_ok() or self.headers.get("X-DeckVM") != "1":
            return self.deny()
        origin = self.headers.get("Origin")
        if origin and origin not in ("http://127.0.0.1:%d" % PORT, "http://localhost:%d" % PORT):
            return self.deny()
        try:
            n = int(self.headers.get("Content-Length") or 0)
            req = json.loads(self.rfile.read(min(n, 20000)) or b"{}")
        except (ValueError, OSError):
            return self.json({"ok": False, "error": "Bad request."}, 400)
        u = urllib.parse.urlparse(self.path).path
        if u == "/api/job" and req.get("name") == "report":
            # a report must work even when a job is stuck, so it runs on its own, outside the one-job-at-a-time rule
            run_script(["report"], timeout=180)
            return self.json({"ok": True, "report": True})
        if u == "/api/job":
            try:
                job = make_job(req)
            except ValueError as e:
                return self.json({"ok": False, "error": str(e)}, 400)
            if job is None:
                return self.json({"ok": False, "error": "Something is still running. Wait for it to finish."}, 409)
            return self.json({"ok": True, "id": job.id})
        if u == "/api/cancel":
            keep = "delete" if req.get("keep") == "delete" else "keep"
            if not cancel_job(keep):
                return self.json({"ok": False, "error": "Nothing is running that can be cancelled."}, 409)
            return self.json({"ok": True})
        if u == "/api/clientnote":
            log("window: %s" % str(req.get("m", ""))[:300].replace("\n", " "))
            return self.json({"ok": True})
        if u == "/api/open-shared":
            out = run_script(["open-shared"], 10)
            return self.json({"ok": True, "text": clean(out).strip()[-300:]})
        if u == "/api/winpass":
            # for the person who needs to unlock Windows by hand: the password is theirs and lives in their own config file
            return self.json({"user": conf_value("WIN_USER", "nerdzap"), "pw": conf_value("WIN_PASS", "")})
        if u == "/api/skipreplug":
            try:
                open(UI_SKIP, "w").close()
            except OSError:
                pass
            return self.json({"ok": True})
        if u == "/api/continue":
            try:
                open(UI_CONTINUE, "w").close()
            except OSError:
                pass
            return self.json({"ok": True})
        if u == "/api/clear_after":
            global AFTER
            with lock:
                AFTER = None
            return self.json({"ok": True})
        if u == "/api/quit":
            self.json({"ok": True})
            threading.Thread(target=shutdown, daemon=True).start()
            return
        self.send(404, "Not found")


class Server(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True
    allow_reuse_address = True


def shutdown():
    time.sleep(0.3)
    for f in (INFO, BUSY_FILE):
        try:
            os.remove(f)
        except OSError:
            pass
    os._exit(0)


def idle_loop():
    while True:
        time.sleep(30)
        with lock:
            busy = JOB is not None and JOB.ended is None
            vm = STATUS.get("vm", "")
        if not busy and vm != "running" and time.monotonic() - LAST_POLL > 1800:
            shutdown()


def main():
    global PORT
    os.makedirs(LOGS, exist_ok=True)
    srv = Server(("127.0.0.1", 0), Handler)
    PORT = srv.server_address[1]
    tmp = INFO + ".tmp"
    with open(tmp, "w") as f:
        try:
            ver = hashlib.sha1(open(os.path.abspath(sys.argv[0]), "rb").read()).hexdigest()[:12]
        except OSError:
            ver = ""
        json.dump({"pid": os.getpid(), "port": PORT, "token": TOKEN, "ver": ver}, f)
    os.chmod(tmp, 0o600)
    os.replace(tmp, INFO)
    threading.Thread(target=status_loop, daemon=True).start()
    threading.Thread(target=idle_loop, daemon=True).start()
    signal.signal(signal.SIGTERM, lambda *a: shutdown())
    print("DeckVM window server on port %d" % PORT, flush=True)
    srv.serve_forever()


ICON_PNG = __import__("base64").b64decode("iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAtbElEQVR42u2deZxcZZX3v+e5t5auXrIDAQQX9l0Ie0BFJIAiMqKAAQKoIzKu8xlGRn3dxgXReWd0xhFfIYEQwr7JImERAoQ9hC2sCUvAhGzdSXe6qrrq3ud5/7hVTSXpJN1dt6qrO+f7+RR8aLqr+9665/ecc57znCM0Lqb0sqVXBTunE5ns7tbxEc+5fZ3Qgsih4AwwFtgTRYmfl4F2EItzT4hjXSjyghEWF7OZV+HtfP+f4cZAGvDvMYBb74a1TBzv2eBAwR0uIgc5yx4ibkeQdN/X4PRRVeplLg5c3jl5VwyvOOfmO+Sx0PjPsG7Zqg3EQErPtVMB6Fspg/IXki3j9rAhH0Nkijh3NMaMW9++e/9hN7gWaUBhU0YGrsJ43fqGLes/ddaudiIP4dwc4zG3sG71KxX/128Ur2CoDcUr/TsEoHnbbRIuPMnBiQLHIdIS3epeYw8rvATU0JUGEgYqVncPEKT0eDq3zsE9AncVxbud7uUr+nz+tyIBMJVqmshM2N9ae6545guCbB95Va7yxhg1dmUYioLtNXSJHFOHW+pCe4MxZkYxu/K5DbxWO9IFoLx6hwBeZsJx4txUEU5DJKVGr2w1YuBcj3Nc50SuDrMr76nwCOqaI5A6u/thacU/wIm7WJApFS5+0Os6KcrIFoMQ8MshgsPNEScXFbMrn93QVkaCAJTjdZtOT9wpkOBHIu4sRJI4V74ZavjK1ioEHiKCcwXn5Crf+T/L55ctqbSbeiThavn+FnB+8/hvW2OvFDFHgysrnFFXX2Hr3VMsP/shkBBjDrQmPMMkM4EtZh+vSCi64eYB9CY1ki1j97TO/KdgpuCsuvqKssXQwOCwc4zY7xbWtb+8YdK80T2A3lU/kRn/VefMLBGzH86Wt/DU+BVls0VwzoqYXZ2T07xEZo0tZudX2JZrZAHwIxUbNcZvavu9GPmJQAacxvmKMiAh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WG2qi8iiQING+7TcKFJzk4UeA4RFoqQoTKfIHR04dKgxk7Fau3V4rtS//XrXNwj8BdRfFup3v5ij6ff4ZocCCNML44evUWOCRbxu1hQz6GyBRx7miMGbf+7XYbqqxsoKaKUqMGHOsZfck7lfWfOmtXO5GHcG6O8ZhbWLf6FdYvnbeN0FGr0QxFKsKD929Oy8Txng0OFNzhInKQs+wh4nYESfd9DVp9rNTNXBy4vHPyrhhecc7Nd8hjofGfYd2yVRssclLvGH+4CUBfXkEfSrlzOpHJ7m4dH/Gc29cJLYgcCs4AY4E99WFVasDLQDuIxbknxLEuFHnBCIuL2cyr8Ha+/89wY/D/AVLkc1eYjX5nAAAAAElFTkSuQmCC")
def guac_js():
    """The Apache Guacamole client library (guacamole-common-js 1.6.0, Apache License 2.0), written next to gui.py as plain text."""
    try:
        with open(os.path.join(BASE, "guacamole-common.js"), "rb") as f:
            return f.read()
    except OSError:
        return b""
PAGE = r'''<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DeckVM</title>
<link rel="icon" type="image/png" href="/icon.png">
<style>
:root{--bg:#050a14;--panel:#0f172a;--panel2:#1e293b;--line:#334155;--text:#f1f5f9;--dim:#94a3b8;--accent:#f97316;--accent2:#ea580c;--tint:#2a1809;--ok:#3ecf8e;--warn:#f0b429;--bad:#ff6b6b;--yt:#cc0000;--coffee:#FFDD00}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--text);font:16px/1.45 Inter,"Segoe UI",system-ui,Roboto,sans-serif;overflow:hidden}
button{font:inherit;color:inherit;cursor:pointer}
#app{display:grid;grid-template-columns:76px 1fr;grid-template-rows:56px 1fr;height:100vh}
#rail{grid-row:1/3;background:var(--panel);border-right:1px solid var(--line);display:flex;flex-direction:column;align-items:stretch;padding:6px 0;gap:2px}
#rail .logo{display:block;text-align:center;padding:9px 0 8px;text-decoration:none;line-height:1}#rail .logo .w{display:block;font:900 14px 'Arial Black','Segoe UI Black',Inter,sans-serif;letter-spacing:-.5px;color:#fff}#rail .logo .w i{font-style:normal;color:var(--accent)}#rail .logo .p{display:block;font-size:10px;margin-top:4px;color:var(--dim);letter-spacing:.5px}
.rb{background:none;border:0;border-left:3px solid transparent;padding:9px 2px 7px;display:flex;flex-direction:column;align-items:center;gap:2px;color:var(--dim);min-height:62px}
.rb .i{font-size:22px;line-height:1}.rb .t{font-size:11px}
.rb:hover{background:var(--panel2);color:var(--text)}
.rb.on{border-left-color:var(--accent);color:var(--text);background:var(--panel2)}
#rail .sp{flex:1}
#top{grid-column:2;display:flex;align-items:center;gap:10px;padding:0 14px;background:var(--panel);border-bottom:1px solid var(--line)}
#chip{display:flex;align-items:center;gap:8px;padding:6px 12px;border-radius:20px;background:var(--panel2);font-size:15px;white-space:nowrap}
.dot{width:10px;height:10px;border-radius:50%;background:var(--dim);flex:none}
.dot.ok{background:var(--ok)}.dot.warn{background:var(--warn);animation:pulse 1.2s infinite}.dot.bad{background:var(--bad)}
@keyframes pulse{50%{opacity:.35}}
#top .sp{flex:1}
.btn{background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:9px 16px;min-height:42px}
.btn:hover{border-color:var(--accent)}
.btn.pri{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:700}
.btn.pri:hover{background:#fb8a3c;border-color:#fb8a3c}
.btn.bad{border-color:#7a3340;color:#ffb3b3}
.btn[disabled]{opacity:.45;pointer-events:none}
.btn.sm{padding:5px 11px;min-height:32px;font-size:14px}
#main{grid-column:2;position:relative;overflow:hidden;background:#000}
#frameWrap{position:absolute;inset:0;display:none;background:#000}
#tdbar{position:absolute;top:8px;left:50%;transform:translateX(-50%);z-index:6;max-width:min(680px,92%);padding:8px 16px;border-radius:999px;background:rgba(15,23,42,.92);border:1px solid var(--accent);color:var(--text);font-size:14px;line-height:1.4;text-align:center;pointer-events:none;display:none}
body.imm #tdbar{display:none!important}
#frameWrap.side{left:350px}
#gwrap{position:absolute;inset:0;z-index:1;display:none;background:#000;overflow:hidden;touch-action:none;user-select:none;-webkit-user-select:none}
#gdisp{position:absolute;left:0;top:0}#gdisp canvas{touch-action:none}
#gmsg{position:absolute;left:50%;top:12px;transform:translateX(-50%);padding:6px 14px;border-radius:999px;background:rgba(15,23,42,.85);border:1px solid var(--line);font-size:14px;display:none;pointer-events:none;z-index:5}
#winframe{position:absolute;inset:0;z-index:2;width:100%;height:100%;border:0;background:#000}
.view{position:absolute;inset:0;overflow:auto;padding:28px 34px;background:var(--bg);display:none}
.view.on{display:block}
#main.n .view,#main.n #frameWrap{top:50px}
body.pan #notice{right:430px}
#view-setup.side{right:auto;width:350px;border-right:1px solid var(--line);padding:22px 20px}
h1{font-size:26px;margin:0 0 6px}h2{font-size:19px;margin:0 0 10px}
.dim{color:var(--dim)}.small{font-size:14px}
.cards{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:14px 0}
.card{background:var(--panel);border:2px solid var(--line);border-radius:12px;padding:12px 14px;cursor:pointer}
.card.on{border-color:var(--accent);background:var(--tint)}
.card b{display:block}.card .tag{float:right;font-size:12px;color:var(--ok)}
.row{display:flex;align-items:center;gap:12px;margin:10px 0}
.row label{min-width:170px;width:170px}
input[type=range]{flex:1;height:30px}
.steps{list-style:none;padding:0;margin:14px 0}
.steps li{display:flex;gap:10px;align-items:flex-start;padding:7px 0;color:var(--dim)}
.steps li .m{width:22px;text-align:center;flex:none}
.steps li.done{color:var(--text)}.steps li.done .m{color:var(--ok)}
.steps li.cur{color:var(--text);font-weight:600}
.bar{height:10px;background:var(--panel2);border-radius:6px;overflow:hidden;margin:6px 0 2px}
.bar i{display:block;height:100%;background:var(--accent);width:0;transition:width .5s}
.bar.ind i{width:35%;animation:slide 1.4s infinite ease-in-out}
@keyframes slide{0%{margin-left:-35%}100%{margin-left:100%}}
.center{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;height:100%;gap:12px}
.center.top{justify-content:flex-start;padding-top:4px}
.askbar{order:-1;align-self:stretch;background:rgba(249,115,22,.18);border:2px solid var(--accent);border-radius:14px;padding:12px 18px;font-size:19px;font-weight:700;color:#fff;margin:0 auto 6px;max-width:760px}
.spin{width:44px;height:44px;border:5px solid var(--panel2);border-top-color:var(--accent);border-radius:50%;animation:rot 1s linear infinite}
@keyframes rot{to{transform:rotate(360deg)}}
#notice{position:absolute;left:0;right:0;top:0;z-index:5;display:none;padding:10px 16px;gap:12px;align-items:center;background:#3a1c22;border-bottom:1px solid #7a3340}
#notice.info{background:#2a1809;border-bottom-color:#9a4a12}
#notice.on{display:flex}#notice .x{flex:1}
#panel{position:absolute;top:56px;right:0;bottom:0;width:430px;max-width:100%;background:var(--panel);border-left:1px solid var(--line);z-index:4;display:none;flex-direction:column}
#panel.on{display:flex}
#ph{display:flex;align-items:center;padding:12px 16px;border-bottom:1px solid var(--line)}#ph b{flex:1;font-size:18px}
#pb{padding:16px;overflow:auto;flex:1}
.dev{display:flex;gap:10px;align-items:center;padding:10px 12px;border:2px solid var(--line);border-radius:10px;margin:8px 0;cursor:pointer;background:var(--panel2)}
.dev.on{border-color:var(--accent)}.dev .n{flex:1}
pre.log{background:#030712;border:1px solid var(--line);border-radius:8px;padding:10px;margin:8px 0;font:12.5px/1.4 ui-monospace,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word;max-height:calc(100vh - 220px);overflow:auto}
textarea.rep{width:100%;height:240px;background:#030712;color:var(--text);border:1px solid var(--line);border-radius:8px;font:12px ui-monospace,monospace}
.tabs{display:flex;gap:6px;margin-bottom:8px}.tabs .btn.on{border-color:var(--accent);background:var(--tint)}
ol.how{padding-left:20px}ol.how li{margin:6px 0}
.uactrow{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px;margin-top:10px}
.pill{display:inline-block;padding:2px 9px;border-radius:12px;background:var(--panel2);font-size:13px}
.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}
a{color:var(--accent)}input[type=range],input[type=checkbox]{accent-color:var(--accent)}
#bmc{display:inline-block;line-height:0;border-radius:8px;flex:none}#bmc img{display:block;height:36px;width:auto;aspect-ratio:217/50;border-radius:8px}
#bmc.fb{background:var(--coffee);color:#000;font:700 15px Inter,system-ui,sans-serif;line-height:36px;padding:0 14px}
#view-setup.on{display:flex;flex-direction:column}#view-setup.on>*{flex:none}
.tipwrap{margin-top:auto;padding-top:14px}
.tip{position:relative;overflow:hidden;background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--accent);border-radius:10px;min-height:60px}
.tip .tl{position:absolute;left:0;right:0;top:0;padding:12px 16px;opacity:0;pointer-events:none;transition:opacity .9s ease-in-out}
.tip .tl.on{opacity:1;pointer-events:auto}.tip .dim{font-size:13px}
.ytbtn{display:inline-flex;align-items:center;gap:8px;background:var(--yt);color:#fff;border-radius:8px;padding:9px 16px;text-decoration:none;font-weight:700}
.about h3{margin:18px 0 6px;font-size:15px;color:var(--accent);text-transform:uppercase;letter-spacing:.6px}
.about ul{margin:6px 0;padding-left:20px}.about li{margin:3px 0}
.about .big{font:900 30px 'Arial Black','Segoe UI Black',Inter,sans-serif;letter-spacing:-1px;color:#fff}.about .big i{font-style:normal;color:var(--accent)}
#modal{position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:20;display:none;align-items:center;justify-content:center;padding:16px}
#modal.on{display:flex}
#modal .box{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:20px 22px;max-width:540px;width:100%}
#modal .bt{display:flex;flex-direction:column;gap:8px;margin-top:14px}
.dev .cb{font-size:20px;line-height:1}
hr.sep{border:0;border-top:1px solid var(--line);margin:16px 0}
.note{font-size:13.5px;color:var(--warn);margin:6px 0}
@media (max-height:760px){
 #app{grid-template-rows:48px 1fr}#panel{top:48px}
 .view{padding:14px 22px}h1{font-size:21px}h2{font-size:17px}
 .cards{gap:6px;margin:8px 0}.card{padding:6px 11px}.card .small{font-size:12.5px}
 .row{margin:5px 0}.row label{min-width:185px;width:185px}
 .rb{min-height:48px;padding:5px 2px 3px}.rb .i{font-size:18px}.rb .t{font-size:10px}
 #rail .logo{padding:5px 0 3px}#rail{padding:3px 0;gap:0}
 .btn{min-height:36px;padding:6px 13px}#top{gap:8px;padding:0 10px}#chip{padding:4px 10px;font-size:14px}
 #bmc img{height:32px}
 #view-setup.side{padding:12px 14px}.steps{margin:8px 0}.steps li{padding:4px 0}
 .tip .tl{padding:8px 12px}.tipwrap{padding-top:8px}
}
@media (max-width:1150px){#top .pill{display:none}}
body.imm #app,body.pop #app{grid-template-columns:0 1fr;grid-template-rows:0 1fr}body.imm #main,body.pop #main{grid-row:1/3}body.imm #rail,body.imm #top,body.pop #rail,body.pop #top{display:none}
body.imm #frameWrap.side,body.pop #frameWrap.side{left:0}body.imm .view.side{display:none}
body.pop .view,body.pop #panel,body.pop #notice,body.pop #modal{display:none!important}body.pop #main.n #frameWrap{top:0}
.dz{margin-top:26px;border:1px solid #b4283a;border-radius:12px;padding:4px 16px 14px;background:rgba(180,40,58,.08)}.dz h2{color:#ff9aa5;margin-bottom:4px}
#toast{position:fixed;left:50%;bottom:22px;transform:translateX(-50%);z-index:80;max-width:620px;padding:12px 18px;border-radius:12px;background:rgba(15,23,42,.94);border:1px solid var(--accent);color:var(--text);font-size:15px;line-height:1.45;display:none;text-align:center}
#popmsg{position:absolute;inset:0;z-index:7;display:none;background:var(--bg);align-items:center;justify-content:center;flex-direction:column;gap:14px;text-align:center;padding:30px}
#b-pop{font-size:26px;line-height:1;padding:4px 14px;min-height:42px}
#imm{display:none;position:fixed;left:50%;top:0;transform:translateX(-50%);z-index:60;height:30px;padding:0 18px;border-radius:0 0 12px 12px;border:1px solid var(--line);border-top:0;background:rgba(15,23,42,.7);color:var(--text);font-size:14px;opacity:.55}
body.imm #imm{display:block}
</style></head>
<body><div id="toast"></div><button id="imm" data-act="fullscreen" title="Show the DeckVM menus again">⛶ Exit fullscreen</button><div id="app">
<nav id="rail">
  <a class="logo" href="https://nerdzap.com" target="_blank" rel="noopener" title="nerdzap.com"><span class="w">NERD<i>ZAP</i></span><span class="p">DeckVM</span></a>
  <button class="rb on" data-act="panel" data-p="" id="rb-win" title="Show the Windows screen"><span class="i">🖥</span><span class="t">Windows</span></button>
  <button class="rb" data-act="panel" data-p="xbox" title="Update an Xbox controller's firmware"><span class="i">🎮</span><span class="t">Controller</span></button>
  <button class="rb" data-act="panel" data-p="usb" title="Give any USB device to Windows"><span class="i">🔌</span><span class="t">USB</span></button>
  <button class="rb" data-act="panel" data-p="tools" title="Shared folder, eject the install disc, repair"><span class="i">🧰</span><span class="t">Tools</span></button>
  <button class="rb" data-act="panel" data-p="settings" title="Memory, cores, advanced options, delete Windows"><span class="i">⚙</span><span class="t">Settings</span></button>
  <button class="rb" data-act="panel" data-p="console" title="What DeckVM and Windows are doing, in detail"><span class="i">📜</span><span class="t">Console</span></button>
  <button class="rb" data-act="panel" data-p="help" title="Help"><span class="i">❓</span><span class="t">Help</span></button>
  <button class="rb" data-act="panel" data-p="about" title="About DeckVM and NerdZap"><span class="i">⚡</span><span class="t">About</span></button>
  <div class="sp"></div>
  <button class="rb" id="rb-full" data-act="fullscreen" title="Windows fills the whole screen. Tap Exit fullscreen at the top to come back"><span class="i">⛶</span><span class="t">Fullscreen</span></button>
</nav>
<header id="top">
  <div id="chip"><span class="dot" id="dot"></span><span id="chiptxt">Loading…</span></div>
  <span id="usbchip" class="pill" style="display:none"></span>
  <div class="sp"></div>
  <button class="btn pri" id="b-start" data-act="start" style="display:none" title="Start your Windows">▶ Start Windows</button>
  <button class="btn" id="b-pop" data-act="pop" style="display:none" title="Pop Windows out into its own window" aria-label="Pop Windows out into its own window">⧉</button>
  <button class="btn bad" id="b-stop" data-act="stop" style="display:none" title="Shut Windows down and give any USB device back to SteamOS">■ Stop</button>
  <button class="btn bad" id="b-cancel" data-act="cancel" style="display:none" title="Stop what DeckVM is doing right now and clean up">✕ Cancel</button>
  <a id="bmc" href="https://www.buymeacoffee.com/nerdzap" target="_blank" rel="noopener noreferrer" aria-label="Buy me a beer on Buy Me a Coffee"><img id="bmcimg" class="bmc-img" src="https://img.buymeacoffee.com/button-api/?text=Buy%20me%20a%20beer&amp;emoji=%F0%9F%8D%BA&amp;slug=nerdzap&amp;button_colour=FFDD00&amp;font_colour=000000&amp;font_family=Poppins&amp;outline_colour=000000&amp;coffee_colour=ffffff" alt="Buy me a beer" width="217" height="50"></a>
</header>
<main id="main">
  <div id="notice"><span class="x" id="noticetxt"></span><span id="noticebtns"></span><button class="btn sm" data-act="dismiss">✕</button></div>
  <div id="frameWrap"><div id="tdbar"></div><iframe id="winframe" title="Windows" allow="clipboard-read; clipboard-write; fullscreen"></iframe><div id="gwrap"><div id="gdisp"></div><div id="gmsg"></div></div></div>
  <div id="popmsg"><div style="font-size:40px">⧉</div><h2>Windows is open in its own window</h2><div class="dim">Only one window can show Windows at a time.</div><div><button class="btn pri" data-act="unpop">Bring it back here</button></div></div>

  <section class="view" id="view-welcome">
    <h1>Set up Windows on your Steam Deck</h1>
    <div class="dim">Pick a version. DeckVM downloads and installs it for you. No password needed.</div>
    <div class="cards" id="editions"></div>
    <div class="row"><label>Memory for Windows</label><input type="range" id="s-ram" min="3" max="10" value="6"><b id="v-ram">6 GB</b></div>
    <div class="row"><label>CPU cores</label><input type="range" id="s-cores" min="1" max="8" value="4"><b id="v-cores">4</b></div>
    <div class="row"><label>Windows disk size</label><input type="range" id="s-disk" min="30" max="256" value="40"><b id="v-disk">40 GB</b></div>
    <div class="row" id="xapp-note" style="display:none"><label></label><div class="note">Xbox Accessories is a Microsoft Store app. This version of Windows may not have a working Store, or may ask for a newer Windows, so the app may not install. Windows 11 Pro or Tiny11 are the best choices for controller updates.</div></div>
    <div class="row"><button class="btn pri" data-act="setup" style="font-size:18px;padding:12px 26px">Set up Windows</button><span class="dim small" id="free"></span></div>
  </section>

  <section class="view" id="view-setup">
    <h1 id="su-title">Setting up Windows</h1>
    <div class="dim small" id="su-sub">Keep your Deck plugged in. DeckVM stops it going to sleep.</div>
    <ul class="steps" id="steps"></ul>
    <div id="su-bar" class="bar ind"><i></i></div>
    <div class="dim small" id="su-note"></div>
    <div class="dim small" style="margin-top:10px">Elapsed: <b id="su-time">0:00</b></div>
    <div id="su-btns" style="margin-top:14px"></div>
    <pre class="log" id="su-log" style="max-height:170px;-webkit-overflow-scrolling:touch;touch-action:pan-y"></pre>
    <div class="tipwrap"><div class="tip" id="tip"><div class="tl on"></div><div class="tl"></div></div></div>
  </section>

  <section class="view" id="view-busy"><div class="center" id="busy-c"><div class="askbar" id="busy-ask" style="display:none"></div><div class="spin"></div><h2 id="busy-t">Working…</h2><div class="dim" id="busy-s"></div><div class="dim small" id="busy-h"></div><div><button class="btn" id="busy-skip" data-act="skipreplug" style="display:none">Skip this step</button></div><div style="margin-top:8px"><button class="btn sm" data-act="panel" data-p="console">Show details</button> <button class="btn sm bad" id="busy-cancel" data-act="cancel" title="Stop what DeckVM is doing right now and clean up">✕ Cancel</button></div></div></section>

  <section class="view" id="view-off"><div class="center">
    <div style="font-size:56px">🖥</div><h1 id="off-t">Windows is off</h1>
    <div class="dim" id="off-s">Your Windows is installed and ready.</div>
    <div><button class="btn pri" data-act="start" style="font-size:18px;padding:12px 26px">▶ Start Windows</button></div>
  </div></section>
</main>
<div id="modal"><div class="box"><h2 id="m-t"></h2><div class="dim" id="m-b"></div><div class="bt" id="m-btns"></div></div></div>
<aside id="panel"><div id="ph"><b id="pt"></b><button class="btn sm" data-act="panel" data-p="">✕ Close</button></div><div id="pb"></div></aside>
</div>
<script src="/guac.js"></script>
<script>
const $=s=>document.querySelector(s);
const EDITIONS=[
 ["11","Windows 11 Pro","8 GB","Full Windows 11 from Microsoft, with the Microsoft Store. The most complete and compatible choice."],
 ["11l","Windows 11 LTSC","5 GB","A plainer Windows 11 for long-term use. Leaves out the Microsoft Store and most bundled apps."],
 ["tiny11","Tiny11","5 GB","An unofficial, slimmed-down Windows 11 with the extras removed. Lighter to run, and keeps the Microsoft Store."],
 ["core11","Tiny11 Core","3 GB","An unofficial, heavily cut-down Windows 11. Very small and fine for simple apps, but expect compatibility problems with others."],
 ["10","Windows 10 Pro","6 GB","Full Windows 10 from Microsoft. Older, and Microsoft no longer supports it, so newer apps may not run."],
 ["10l","Windows 10 LTSC","5 GB","A plainer Windows 10 for long-term use. Leaves out the Microsoft Store and most bundled apps."],
 ["tiny10","Tiny10","4 GB","An unofficial, slimmed-down Windows 10 with the extras removed. Lighter to run."]];
let S=null, panel='', winSel='11', devs=[], logFrom=0, logLines=[], logJob=null, consoleTab='job', reportText='', reportPath='';
/* ---------- touch display: Windows over RDP through Apache Guacamole (taps reach Windows as real touch) ---------- */
const TD={on:false,client:null,tunnel:null,multi:false,fails:0,failUntil:0,connected:false,live:false,t0:0,chk:0,ro:null,rt:0,clipT:0,lastClip:''};
function tdPref(){ return (S&&S.status&&S.status.touch==='1')?'touch':'plain'; }   // opt-in: Settings > Touch display
function tdMsg(txt){ const m=$('#gmsg'); m.textContent=txt||''; m.style.display=txt?'block':'none'; }
function tdFail(why,ms){
  TD.fails++; TD.failUntil=Date.now()+(ms||(TD.fails>=3?120000:15000));
  console.warn('touch display failed:',why); tdStop(); tdMsg(''); if(S) setView(lastView||currentView());
}
/* true once the touch display has painted something that is not plain black */
function tdHasPixels(){
  try{ const c=TD.client.getDisplay().getDefaultLayer().getCanvas(), x=c.getContext('2d'), w=c.width, h=c.height; if(w<8||h<8) return false;
    for(let i=1;i<8;i++) for(let j=1;j<5;j++){ const d=x.getImageData(Math.floor(w*i/8),Math.floor(h*j/5),1,1).data; if(d[0]+d[1]+d[2]>24) return true; }
  }catch(e){}
  return false;
}
function noteBlank(){ notice('The touch display stayed blank, so you are back on the normal display. You can try it again after Stop and Start.','info'); }
async function pwSentence(){ try{ const r=await api('/api/winpass',{}); return r&&r.pw?(' If Windows asks for a password, it is "'+r.pw+'".'):''; }catch(e){ return ''; } }
function tdStop(){
  if(!TD.on) return; TD.on=false;
  if(TD.live&&S&&S.status&&S.status.vm==='running') pwSentence().then(function(t){ if(t){ notice('Switched to the normal display.'+t,'info'); } });   // the console is locked while the touch display was connected
  try{ if(TD.ro) TD.ro.disconnect(); }catch(e){}
  clearInterval(TD.chk); TD.live=false;
  const c=TD.client; TD.client=null; TD.tunnel=null; TD.connected=false; TD.multi=false;
  if(c){ c.onstatechange=null; c.onerror=null; try{ c.disconnect(); }catch(e){} }
  $('#gdisp').innerHTML=''; tdMsg('');
}
function tdStart(){
  if(TD.on) return; TD.on=true; TD.connected=false; TD.multi=false; TD.live=false;
  const wrap=$('#gwrap'), disp=$('#gdisp'); disp.innerHTML='';
  const W=Math.max(320,Math.floor(wrap.clientWidth)), H=Math.max(240,Math.floor(wrap.clientHeight));
  const tun=new Guacamole.WebSocketTunnel('ws://'+location.host+'/tunnel');
  const client=new Guacamole.Client(tun); TD.client=client; TD.tunnel=tun;
  const display=client.getDisplay(), el=display.getElement(); disp.appendChild(el);
  tdMsg('Connecting the touch display…');
  client.onstatechange=function(s){
    if(TD.client!==client) return;
    if(s===3){ TD.connected=true; TD.fails=0; tdMsg(''); TD.t0=Date.now();
      // The plain display stays on screen until Windows really paints through the touch display. If it stays black, give up on it
      clearInterval(TD.chk); TD.chk=setInterval(function(){
        if(TD.client!==client){ clearInterval(TD.chk); return; }
        if(TD.live) return;
        if(tdHasPixels()){ TD.live=true; clearInterval(TD.chk); if(S) setView(lastView||currentView()); }
        else if(Date.now()-TD.t0>40000){ tdFail('stayed blank',600000); noteBlank(); }
      },1500); }
    if(s===5){ if(TD.connected){ TD.failUntil=Date.now()+3000; tdStop(); setView(lastView||currentView()); } else tdFail('closed before it connected'); }
  };
  client.onerror=function(e){ if(TD.client===client) tdFail((e&&e.message)||'error'); };
  tun.onerror=function(e){ if(TD.client===client) tdFail((e&&e.message)||'tunnel error'); };
  client.onmultitouch=function(layer,n){ TD.multi=n>0; };
  // pointer: a real mouse or trackpad, and a one-finger fallback when Windows does not offer touch
  const mouse=new Guacamole.Mouse(el);
  const mfn=function(ms){ client.sendMouseState(ms,true); };
  mouse.onmousedown=mouse.onmouseup=mouse.onmousemove=mfn;
  const ts=new Guacamole.Mouse.Touchscreen(el);
  ts.onmousedown=ts.onmouseup=ts.onmousemove=function(ms){ if(!TD.multi) client.sendMouseState(ms,true); };
  // real multi-touch: each finger goes to Windows as a touch contact, so Windows shows its touch keyboard
  const touch=new Guacamole.Touch(el);
  touch.onEach(['touchstart','touchmove','touchend'],function(e){ if(TD.multi) client.sendTouchState(e.state,true); });
  const kbd=new Guacamole.Keyboard(document);
  const typing=function(){ const a=document.activeElement; return a&&/^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName); };
  kbd.onkeydown=function(k){ if(TD.client!==client||typing()) return true; client.sendKeyEvent(1,k); return false; };
  kbd.onkeyup=function(k){ if(TD.client!==client||typing()) return; client.sendKeyEvent(0,k); };
  client.onclipboard=function(stream,mime){
    if(mime!=='text/plain') return; const r=new Guacamole.StringReader(stream); let d='';
    r.ontext=function(x){ d+=x; }; r.onend=function(){ TD.lastClip=d; try{ navigator.clipboard.writeText(d); }catch(e){} };
  };
  const pushClip=function(){
    if(Date.now()-TD.clipT<1500||!TD.connected) return; TD.clipT=Date.now();
    try{ navigator.clipboard.readText().then(function(x){ if(x&&x!==TD.lastClip&&TD.client===client){ TD.lastClip=x;
      const s=client.createClipboardStream('text/plain'), w=new Guacamole.StringWriter(s); w.sendText(x); w.sendEnd(); } }).catch(function(){}); }catch(e){}
  };
  window.addEventListener('focus',pushClip); wrap.addEventListener('pointerdown',function(){
    pushClip(); try{ const ac=Guacamole.AudioContextFactory.getAudioContext(); if(ac&&ac.state==='suspended') ac.resume(); }catch(e){} });
  TD.ro=new ResizeObserver(function(){ clearTimeout(TD.rt); TD.rt=setTimeout(function(){
    if(TD.client===client&&TD.connected){ client.sendSize(Math.max(320,Math.floor(wrap.clientWidth)),Math.max(240,Math.floor(wrap.clientHeight))); } },600); });
  TD.ro.observe(wrap);
  let audio=[]; try{ audio=Guacamole.AudioPlayer.getSupportedTypes(); }catch(e){}
  let img=['image/png','image/jpeg']; try{ if(document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp')===0) img.push('image/webp'); }catch(e){}
  let tz=''; try{ tz=Intl.DateTimeFormat().resolvedOptions().timeZone||''; }catch(e){}
  client.connect('w='+W+'&h='+H+'&dpi=96&touch=1&tz='+encodeURIComponent(tz)+'&audio='+encodeURIComponent(audio.join(','))+'&image='+encodeURIComponent(img.join(',')));
}
let toastT=0;
function toast(txt,ms){ const t=$('#toast'); t.textContent=txt; t.style.display='block'; clearTimeout(toastT); toastT=setTimeout(function(){ t.style.display='none'; },ms||10000); }
function enterFull(){
  // Only the DeckVM menus are hidden; the window stays an ordinary maximised window, so Steam+X and Windows' own touch keyboard both keep working
  document.body.classList.add('imm');
  toast("Menus hidden. Tap Exit fullscreen at the top to bring them back.",5000);
}
function leaveFull(){
  document.body.classList.remove('imm'); $('#toast').style.display='none';
  if(document.fullscreenElement){ try{ const r=document.exitFullscreen(); if(r&&r.catch) r.catch(function(){}); }catch(e){} }
}
document.addEventListener('fullscreenchange',function(){ if(!document.fullscreenElement) document.body.classList.remove('imm'); });
let removing=false, autoStarted=false, afterDone=null, dismissed=null, reportWanted=false, lastWeb='0', frameEpoch=0, frameShown=-1, lastView='', busySince=0;
/* The Windows screen is shown in an iframe. It is addressed as "localhost" on purpose (the server says if that does not work, and then
   127.0.0.1 is used). To the browser "localhost" and "127.0.0.1" are different sites, so the screen runs in its own process, apart from
   this page. With the same address both share one process and the Windows screen lags on roughly a third of loads. */
function frameUrl(){
  const h=window.SAMEHOST?'127.0.0.1':((typeof S!=='undefined'&&S&&S.status&&S.status.vhost)||'localhost');
  return 'http://'+h+':8006/?resize=scale';
}
function loadFrame(){ $('#winframe').src=frameUrl(); }
function noteWin(m){ try{ api('/api/clientnote',{m:String(m).slice(0,300)}).catch(function(){}); }catch(e){} }
document.addEventListener('DOMContentLoaded',function(){
  const f=document.getElementById('winframe');
  f.addEventListener('load',function(){
    if(!/:8006\//.test(f.src)) return;
    const r=f.getBoundingClientRect();
    noteWin('viewer loaded from '+f.src.replace(/\?.*$/,'')+', area '+Math.round(r.width)+'x'+Math.round(r.height)+', '+document.visibilityState+(document.hasFocus()?', focused':', not focused'));
    // The screen was loaded while it had no size (hidden behind another view). Its scaling is then worked out for a 0x0 area and clicks can land in the wrong place,
    // so load it once more as soon as it has a real size.
    if((r.width<50||r.height<50)&&!f.__refit){
      f.__refit=true; let n=0;
      const t=setInterval(function(){
        const q=f.getBoundingClientRect(); n++;
        if(q.width>=200&&q.height>=200&&f.style.display!=='none'&&/:8006\//.test(f.src)){ clearInterval(t); f.__refit=false; noteWin('viewer reloaded: it now has area '+Math.round(q.width)+'x'+Math.round(q.height)); loadFrame(); }
        else if(n>120){ clearInterval(t); f.__refit=false; }
      },500);
    }
  });
});
/* ---------- pop-out: the same display in its own window. Only one window talks to Windows at a time ---------- */
const POP=/[?&]pop=1/.test(location.search);
let popAlive=0, popDone=false, popHB=0, BC=null; try{ BC=new BroadcastChannel('deckvm-pop'); }catch(e){}
function isPopped(){ return !POP&&Date.now()-popAlive<6000; }
if(BC){
  BC.onmessage=function(e){ const m=e.data;
    if(POP){ if(m==='pop-close'){ popDone=true; clearInterval(popHB); tdStop(); try{ window.close(); }catch(x){} if(S) setView('win'); } return; }
    if(m==='pop-here'){ const was=isPopped(); popAlive=Date.now(); if(!was&&S) setView(lastView||currentView()); }
    else if(m==='pop-gone'){ popAlive=0; if(S) setView(lastView||currentView()); } };
  if(POP){ popHB=setInterval(function(){ BC.postMessage('pop-here'); },2000); BC.postMessage('pop-here'); window.addEventListener('pagehide',function(){ BC.postMessage('pop-gone'); }); }
}
if(POP) document.body.classList.add('pop');

async function api(path, body){
  const o=body===undefined?{}:{method:'POST',headers:{'X-DeckVM':'1','Content-Type':'application/json'},body:JSON.stringify(body)};
  const r=await fetch(path,o);
  if(r.status===403) throw new Error('forbidden');
  return r.json();
}
function setHTML(el,h){ if(el&&el.__h!==h){ el.innerHTML=h; el.__h=h; } }
let failPolls=0;
function devList(){ return panel==='xbox'?devs.filter(d=>d.ms):devs.filter(d=>!d.internal); }
async function job(body){
  if($('#notice').classList.contains('info')) clearNotice();   // an old 'Saved' or 'Copied' should not hang around while something new starts
  const r=await api('/api/job',body);
  if(!r.ok) notice(r.error||'That did not work.','bad');
  poll(); return r;
}
function esc(s){return String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]))}
let noticeTimer=null;
// Plain information fades away by itself (about 6 to 15 s, longer for longer text). Errors and anything with a button stay until dismissed.
function notice(txt,kind,btns){const n=$('#notice');$('#main').classList.add('n');$('#noticetxt').textContent=txt;n.className='on '+(kind==='info'?'info':'');$('#noticebtns').innerHTML=btns||'';
  clearTimeout(noticeTimer); noticeTimer=null;
  if(kind==='info'&&!btns){ const mine=txt; noticeTimer=setTimeout(function(){ if($('#noticetxt').textContent===mine) clearNotice(); }, Math.min(15000,Math.max(6000,3500+String(txt).length*60))); } }
function clearNotice(){ clearTimeout(noticeTimer); noticeTimer=null; $('#notice').className=''; $('#main').classList.remove('n'); }
const EST={tiny11:5.7e9,core11:3.3e9};
function fmtB(n){ if(n>=1073741824) return (n/1073741824).toFixed(2)+' GB'; if(n>=1048576) return Math.round(n/1048576)+' MB'; return Math.max(0,Math.round(n/1024))+' KB'; }
function fmt(sec){sec=Math.max(0,Math.floor(sec));const m=Math.floor(sec/60);return m+':'+String(sec%60).padStart(2,'0')}

/* ---------- welcome form ---------- */
function buildEditions(){
  $('#editions').innerHTML=EDITIONS.map(e=>`<div class="card ${e[0]===winSel?'on':''}" data-act="pick" data-w="${e[0]}"><b>${esc(e[1])}</b><span class="dim small">${esc(e[2])} download. ${esc(e[3])}</span></div>`).join('');
}
for(const [id,suf] of [['ram',' GB'],['cores',''],['disk',' GB']]) $('#s-'+id).oninput=e=>$('#v-'+id).textContent=e.target.value+suf;

/* ---------- derive what to show ---------- */
function currentView(){
  const st=S.status, j=S.job, inst=st.installed==='1', running=j&&j.running;
  if(running&&j.name==='auto') return 'setup';
  if(running&&['start','stop','xbox','usb','reset','uninstall','cancel','repair'].includes(j.name)) return 'busy';
  if(!inst) return 'welcome';
  if(st.vm==='running') return 'win';
  return 'off';
}
function setView(v){
  if(POP) v=(S.status.vm==='running')?'win':'off';
  if(POP&&popDone){ tdStop(); $('#frameWrap').style.display='block'; $('#gwrap').style.display='none'; $('#winframe').style.display='none'; const pm=$('#popmsg'); pm.innerHTML='<div style="font-size:40px">⧉</div><h2>Windows is back in the main DeckVM window</h2><div class="dim">You can close this window.</div>'; pm.style.display='flex'; return; }
  for(const id of ['welcome','setup','busy','off']) $('#view-'+id).classList.toggle('on',v===id&&!POP);
  const popped=(v==='win')&&isPopped();
  $('#popmsg').style.display=popped?'flex':'none';
  const showFrame=!popped&&((v==='win')||(v==='setup'&&S.status.web==='1'));
  $('#frameWrap').style.display=showFrame?'block':'none';
  if(!showFrame||(v!=='win'&&v!=='setup')) leaveFull();
  $('#rb-full').style.display=(showFrame&&(v==='win'||v==='setup'))?'':'none';   // nothing to make bigger while Windows is off
  const useTouch=showFrame&&(v==='win')&&S.status.rdp==='1'&&S.status.usb_session!=='1'&&tdPref()==='touch'&&typeof Guacamole!=='undefined'&&Date.now()>=TD.failUntil;
  $('#gwrap').style.display=useTouch?'block':'none';
  if(useTouch) tdStart(); else tdStop();
  const touchLive=useTouch&&TD.live;                 // until then the plain display shows Windows, so there is never a blank screen
  $('#winframe').style.display=touchLive?'none':'';
  { // touch display is on in Settings but Windows is still on the normal screen: say why, so the switch later does not look like a fault
    const tb=$('#tdbar'), waiting=showFrame&&v==='win'&&tdPref()==='touch'&&S.status.touch_session==='1'&&S.status.usb_session!=='1'&&!touchLive&&typeof Guacamole!=='undefined'&&Date.now()>=TD.failUntil;
    tb.style.display=waiting?'block':'none';
    if(waiting) tb.textContent=S.status.rdp==='1'?'Switching to the touch display…':'Windows is starting. The touch display switches on when it is ready.';
  }
  $('#frameWrap').classList.toggle('side',v==='setup');
  $('#view-setup').classList.toggle('side',v==='setup'&&showFrame);
  if(touchLive){ if(frameShown!==-1){ $('#winframe').src='about:blank'; frameShown=-1; } }
  else if(showFrame && S.status.web==='1'){
    if(lastWeb!=='1') frameEpoch++;
    if(frameShown!==frameEpoch){ loadFrame(); frameShown=frameEpoch; }
  }
  if(S.status.web!==lastWeb){ lastWeb=S.status.web; }
  lastView=v;
}

/* ---------- render ---------- */
function render(){
  const st=S.status, j=S.job, v=currentView(), running=j&&j.running;
  setView(v);
  // chip
  let txt='', dot='';
  if(running){txt=j.label+'…';dot='warn';}
  else if(st.installed!=='1'){ if(st.vm==='running'){txt='Windows is still installing…';dot='warn';} else {txt='Windows not set up';dot='';} }
  else if(st.vm==='running'&&st.web==='1'){txt='Windows is running';dot='ok';}
  else if(st.vm==='running'){txt='Windows is starting…';dot='warn';}
  else {txt='Windows is off';dot='';}
  $('#chiptxt').textContent=txt; $('#dot').className='dot '+dot;
  const uc=$('#usbchip');
  if(st.usb_session==='1'){
    const o=st.usb_owner; uc.style.display='';
    // Controllers restart several times during a firmware update (gone for ~2 s, then ~5 s before Windows
    // has them again). That is normal, so say so for the first 25 s before showing the plain warning.
    const okNow=o.includes('usbfs');
    if(okNow){ window._usbLostAt=0; } else if(!window._usbLostAt){ window._usbLostAt=Date.now(); }
    const lostFor=window._usbLostAt?(Date.now()-window._usbLostAt)/1000:0;
    const lostTxt=lostFor<25
      ?'🎮 Device restarting, reconnecting to Windows… <span class="dim">(normal during an update)</span>'
      :(o==='unplugged'?'🎮 Device unplugged':'🎮 Device not claimed yet – try unplugging and replugging it');
    uc.innerHTML=(okNow?'🎮 Windows has your device <span class="ok">✓</span>':lostTxt)+(st.capture==='1'?' · <span class="warn" title="USB recording is on: the attached device\'s USB messages are being saved to a file in the logs folder on this Deck">⏺ Recording USB</span>':'');
  } else uc.style.display='none';
  $('#b-start').style.display=(st.installed==='1'&&st.vm!=='running'&&!running)?'':'none';
  $('#b-stop').style.display=(st.vm==='running'&&!running)?'':'none';
  $('#b-cancel').style.display=(running&&!['cancel','report','settings'].includes(j.name)&&v!=='setup'&&v!=='busy')?'':'none';
  { const xa=$('#xapp-note'); if(xa) xa.style.display=(['core11','tiny10','11l','10l','10'].includes(winSel)&&$('#view-welcome').classList.contains('on'))?'':'none'; }
  if(panel==='tools') updateTools();
  if(panel==='settings') updateRunNow();
  $('#b-pop').style.display=(st.vm==='running')?'':'none';
  $('#free').textContent=st.free_gb?('Free space: '+st.free_gb+' GB'):'';

  if(v==='setup') renderSetup();
  if(v==='busy') renderBusy();
  if(v==='off'){ $('#off-t').textContent=st.edition_name+' is off'; }
  if(panel==='xbox'||panel==='usb') renderUsbBody();
  failures();
  autoFlow();
}

let curKey=null;
function failures(){
  const j=S.job, st=S.status, running=j&&j.running;
  let key=null, txt='', kind='bad', btns='';
  if(j&&!running&&j.rc!==0&&j.rc!==null&&!['report'].includes(j.name)){
    key=j.id;
    if(j.cancelled){ txt='Cancelled.'; kind='info'; }
    else if(j.rc===130){
      kind='info';
      const R={xbox:'Cancelled. Without your password DeckVM cannot hand the device to Windows, so nothing was changed and your controller still works in SteamOS.',
               usb:'Cancelled. Without your password DeckVM cannot hand the device to Windows, so nothing was changed.',
               stop:'Cancelled. Without your password DeckVM cannot give the USB device back to SteamOS, so Windows was not stopped. Press Stop to try again.',
               reattach:'Cancelled. Without your password DeckVM cannot reconnect the device. Nothing was changed.',
               repair:'Cancelled. The controller drivers are still switched off. Press the button to try again.',
               start:'Cancelled. Windows was not started.'};
      txt=R[j.name]||'Cancelled. Nothing was changed.';
    }
    else if(j.single){
      txt='DeckVM runs a single Windows at the moment, and one is already set up here ('+st.edition_name+'). To use a different one, delete the current Windows first.';
      btns='<button class="btn sm" data-act="start">Start my current Windows</button> <button class="btn sm bad" data-act="replace">Delete it and set up the new one</button> ';
    } else {
      txt=(j.fail||'Something went wrong.')+' ';
      btns='<button class="btn sm" data-act="report">Make a report</button> <button class="btn sm" data-act="panel" data-p="console">Details</button> ';
    }
  } else if(st.crash==='1'&&st.vm!=='running'&&!running){
    key='crash';
    txt='Windows stopped unexpectedly (the virtual machine crashed). Your controller is being given back to SteamOS. If you were in the middle of an update, start controller update mode again and open the Accessories app: it may offer to finish the update. Please make a report.';
    btns='<button class="btn sm" data-act="report">Make a report</button> ';
  } else if(st.driver_block==='1'&&st.vm!=='running'&&!running){
    key='drv';
    txt="SteamOS's Xbox controller drivers are still switched off from an earlier USB session, so your controller may not work in SteamOS.";
    btns='<button class="btn sm" data-act="repair">Put them back</button> ';
  }
  if(key&&dismissed!==key){
    if(curKey!==key){
      curKey=key; notice(txt,kind,btns);
      if(kind==='info') setTimeout(()=>{ if(curKey===key){ dismissed=key; curKey=null; clearNotice(); } },15000);
    }
  } else if(curKey&&(!key||dismissed===key)){ curKey=null; clearNotice(); }
}

const TIPS=[
 ['☕ <b>Grab a brew</b>, this will take a while…','Windows downloads and installs itself. DeckVM keeps your Deck awake.'],
 ['🎁 <b>Free PC games</b>','Every free game on Steam, Epic, GOG and Prime Gaming, in one place. Claim them before they\'re gone at '+'<a href="https://nerdzap.com/free-games/" target="_blank" rel="noopener">nerdzap.com/free-games</a>'],
 ['📰 <b>Tech news, guides and tools</b>','Catch the latest at <a href="https://nerdzap.com" target="_blank" rel="noopener">nerdzap.com</a>'],
 ['▶ <b>Subscribe to NerdZap on YouTube</b>','<a href="https://www.youtube.com/@NerdZap?sub_confirmation=1" target="_blank" rel="noopener">youtube.com/@NerdZap</a> (please)'],
 ['🕹️ <b>Back in SteamOS?</b>','Add Xbox Cloud Gaming, GeForce Now, Netflix and more to your Steam library in one click with <a href="https://nerdzap.com/tools/deckzap/" target="_blank" rel="noopener">DeckZap</a>, free at nerdzap.com'],
 ['🧰 <b>Optimise Windows</b>','Want the most from your handheld? Grab the debloat scripts and tweaks I use at <a href="https://nerdzap.com/downloads/#windows-optimisation" target="_blank" rel="noopener">nerdzap.com/downloads</a>'],
 ['🎮 <b>First boot</b>','The first start takes a few extra minutes while Windows sets itself up.'],
 ['📡 <b>Can\'t connect to a game?</b>','Check if it\'s down for everyone, live: <a href="https://nerdzap.com/status/" target="_blank" rel="noopener">nerdzap.com/status</a>'],
 ['📱 <b>Follow the journey</b>','<a href="https://x.com/TheNerdZap" target="_blank" rel="noopener">X</a> · <a href="https://bsky.app/profile/nerdzap.com" target="_blank" rel="noopener">Bluesky</a> · <a href="https://instagram.com/thenerdzap" target="_blank" rel="noopener">Instagram</a> · <a href="https://facebook.com/nerdzap" target="_blank" rel="noopener">Facebook</a>'],
 ['🍺 <b>Want to say cheers?</b>','Buy me a beer at <a href="https://www.buymeacoffee.com/nerdzap" target="_blank" rel="noopener">buymeacoffee.com/nerdzap</a>']];
let tipI=-1, tipAct=0, tipW=0;
function tipHtml(i){ return TIPS[i][0]+'<div class="dim">'+TIPS[i][1]+'</div>'; }
/* The box is as tall as the tallest tip, so nothing below or above it moves when the tip changes. */
function sizeTip(el){
  const w=el.clientWidth; if(!w||w===tipW) return; tipW=w;
  const m=document.createElement('div'); m.className='tl'; m.style.cssText='visibility:hidden;opacity:0;pointer-events:none';
  el.appendChild(m); let h=0;
  for(let i=0;i<TIPS.length;i++){ m.innerHTML=tipHtml(i); h=Math.max(h,m.offsetHeight); }
  el.removeChild(m); el.style.height=(h+2)+'px';
}
/* Two layers cross-fade, so the old tip fades out while the new one fades in and the box is never empty. */
function nextTip(){
  const el=$('#tip'); if(!el||!$('#view-setup').classList.contains('on')) return;
  sizeTip(el);
  const L2=el.querySelectorAll('.tl'), cur=L2[tipAct], nxt=L2[1-tipAct];
  tipI=(tipI+1)%TIPS.length; nxt.innerHTML=tipHtml(tipI);
  nxt.classList.add('on'); cur.classList.remove('on'); tipAct=1-tipAct;
}
function renderSetup(){
  const st=S.status,j=S.job,p=S.progress||{};
  const ed=EDITIONS.find(e=>e[0]===st.edition)||['','Windows'];
  $('#su-title').textContent='Setting up '+ed[1];
  let idx=0; const stage=S.stage;
  if(stage==='pull') idx=1; else if(stage==='install') idx=p.booted?3:2; else if(stage==='ready') idx=4;
  const names=['Check your Deck','Download the VM software','Download Windows','Install Windows','Finish up'];
  const pu=p.pull||{parts:0,done:0}, pTot=Math.max(8,pu.parts);
  const extra=i=>i===2&&p.pct!=null?' — '+p.pct+'%':(i===1&&pu.done?' — '+pu.done+' of about '+pTot+' parts':(i===1&&pu.parts?' — '+pu.parts+' parts':''));
  $('#steps').innerHTML=names.map((n,i)=>`<li class="${i<idx?'done':i===idx?'cur':''}"><span class="m">${i<idx?'✓':i===idx?'●':'○'}</span><span>${n}${i===idx?extra(i):''}</span></li>`).join('');
  const bar=$('#su-bar');
  if(idx===2&&p.pct!=null){bar.className='bar';bar.firstElementChild.style.width=p.pct+'%';}
  else if(idx===2&&p.prep){bar.className='bar ind';bar.firstElementChild.style.width='';}
  else if(idx===2&&p.downloading&&p.bytes!=null&&EST[st.edition]&&!p.total){bar.className='bar';bar.firstElementChild.style.width=Math.min(97,Math.round(p.bytes/EST[st.edition]*100))+'%';}
  else if(idx===1&&pu.done){bar.className='bar';bar.firstElementChild.style.width=Math.min(100,Math.round(pu.done/pTot*100))+'%';}
  else {bar.className='bar ind';bar.firstElementChild.style.width='';}
  let note='';
  if(idx===1) note='Downloading the virtual machine software (about 700 MB).';
  if(idx===2){
    note=p.downloading?('Downloading '+ed[1]+'.'):'Getting Windows ready…';
    if(p.prep){ note='The download has finished. Windows is now preparing the install files. This can take several minutes and nothing moves on screen.'; }
    else if(p.bytes!=null){
      let tot=p.total?p.total:((p.pct&&p.pct>=10)?Math.max(p.bytes,Math.round(p.bytes*100/p.pct)):(EST[st.edition]||0));
      if(tot&&tot<p.bytes) tot=0;
      let d=p.bytes<1048576?'Starting the download…':fmtB(p.bytes)+(tot&&p.bytes>=1048576?(p.total?' of ':' of about ')+fmtB(tot):' downloaded')+(p.speed>0?' · '+fmtB(p.speed)+'/s':'');
      if(tot&&p.speed>0&&tot>p.bytes){ const m=Math.ceil((tot-p.bytes)/p.speed/60); d+=' · about '+(m>=2?m+' minutes':'a minute')+' left'; }
      note+='  '+d;
    }
  }
  if(idx===3) note='Windows installs by itself and restarts a few times. This is normal. You can watch it on the right.';
  $('#su-note').textContent=note;
  $('#su-time').textContent=fmt(S.now-j.started);
  const btns=$('#su-btns');
  const cbtn='<button class="btn bad" data-act="cancel" title="Stop the setup. You choose whether to keep what was downloaded.">✕ Cancel setup</button>';
  if(idx===3&&S.now-j.started>240) setHTML(btns,cbtn+'<div class="dim small" style="margin-top:10px">DeckVM finishes by itself when Windows reports it is done. Only use this if it seems stuck.</div><div style="margin-top:8px"><button class="btn" data-act="continue">I can see the Windows desktop — finish now</button></div>');
  else setHTML(btns,cbtn);
  { const lg=$('#su-log'), txt=(j.tail||[]).join('\n');
    if(lg.__t!==txt){ const stick=lg.scrollTop+lg.clientHeight>=lg.scrollHeight-24; lg.textContent=txt; lg.__t=txt; if(stick) lg.scrollTop=lg.scrollHeight; }
    lg.style.display=idx===3?'none':'block'; }
}
function renderBusy(){
  const j=S.job,st=S.status;
  $('#busy-t').textContent=j.label+'…';
  $('#busy-s').textContent=j.step||'';
  let h='';
  if(['xbox','usb'].includes(j.name)) h='A small window will ask for your Deck password. Windows restarts briefly with your device attached.';
  const replug=['xbox','usb'].includes(j.name)&&/Plug the controller in again/.test(j.step||'');
  if(replug) h="Unplug the controller's cable, wait a second, then plug it back in. DeckVM carries on by itself. Use Skip if you can't replug it.";
  if(j.name==='stop') h='Shutting Windows down. This can take a minute or two. If it takes longer, press "Switch off now".';
  if(j.name==='repair') h='Putting the controller drivers back. This may ask for your Deck password.';
  if(j.name==='cancel') h='Stopping Windows and putting things back.';
  const bh=$('#busy-h'); bh.textContent=h; bh.style.cssText=replug?'font-size:22px;font-weight:700;color:#fff;background:rgba(249,115,22,.18);border:2px solid var(--accent);border-radius:14px;padding:16px 22px;margin:14px auto;max-width:560px':'';
  if(replug) $('#busy-t').textContent='🔌 Unplug and replug the controller';
  $('#busy-skip').style.display=replug?'':'none';
  const cb=$('#busy-cancel'); if(cb){ cb.style.display=(j.name==='cancel')?'none':''; cb.textContent=(j.name==='stop')?'⏻ Switch off now':'✕ Cancel'; cb.title=(j.name==='stop')?'Do not wait for Windows to shut down: switch it off straight away':'Stop what DeckVM is doing right now and clean up'; }
  // while the Deck password box is open it sits in the middle of the window, so the explanation moves to the top, above it
  const ask=st.ask||'', ab=$('#busy-ask');
  ab.style.display=ask?'':'none';
  if(ask) ab.innerHTML='🔒 A window in the middle of the screen is asking for your Deck password '+ask.replace(/&/g,'&amp;').replace(/</g,'&lt;')+'.<div style="font-size:15px;font-weight:400;margin-top:4px">It is the password you set for your Deck (the one for <code>passwd</code>). Windows itself never needs it.</div>';
  $('#busy-c').classList.toggle('top',!!ask);
  if(ask) $('#busy-h').textContent='';
}

function autoFlow(){
  const j=S.job, running=j&&j.running;
  if(S.pending&&S.pending.length&&!running&&!autoStarted){autoStarted=true;lastAutoArgs=S.pending.slice();api('/api/job',{name:'auto',args:S.pending}).then(()=>poll());}
  if(j&&!j.running&&j.name==='auto'&&j.rc===0&&afterDone!==j.id){
    afterDone=j.id;
    const a=S.after;
    if(a){ api('/api/clear_after',{});
      if(a==='xbox') openPanel('xbox');
      if(a==='start'&&S.status.vm!=='running') job({name:'start'}); }
    notice('Windows is ready.','info');
    setTimeout(()=>{ if($('#notice').classList.contains('info')) clearNotice(); },6000);
  }
  if(j&&!j.running&&j.rc===0&&doneFor!==j.id&&['cancel','eject','repair','reattach'].includes(j.name)){
    doneFor=j.id;
    let m=''; for(const ln of (j.tail||[])){ const x=ln.match(/\[ OK \]\s*(.*)/); if(x) m=x[1]; else if(/^\s+(No disc|Windows is not)/.test(ln)) m=ln.trim(); }
    if(j.name==='reattach') m='Done. Windows got the device back. If the Xbox Accessories app still does not list it, unplug the cable and plug it back in. DeckVM hands it back to Windows by itself.';
    if(!m) m={cancel:'Cancelled.',eject:'Done.',repair:'Done.'}[j.name]||'Done.';
    curKey=null; notice(m,'info'); setTimeout(()=>{ if($('#noticetxt').textContent===m) clearNotice(); }, j.name==='reattach'?20000:12000);
  }
  if(j&&!j.running&&j.name==='report'&&reportWanted){reportWanted=false;loadReport();}
}

/* ---------- panels ---------- */
function openPanel(p){
  panel=p||'';
  document.body.classList.toggle('pan',!!panel);
  document.querySelectorAll('.rb[data-p]').forEach(b=>b.classList.toggle('on',b.dataset.p===panel));
  const el=$('#panel'); if(!panel){el.classList.remove('on');return;}
  el.classList.add('on');
  const T={xbox:'Controller update',usb:'USB devices',tools:'Tools',settings:'Settings',console:'Console',help:'Help',about:'About DeckVM'};
  $('#pt').textContent=T[panel]||'';
  const b=$('#pb');
  if(panel==='xbox'||panel==='usb'){ b.innerHTML='<div id="ubody"></div><div id="devlist"></div><div id="uact"></div>'; renderUsbBody(); loadDevices(); }
  if(panel==='tools') buildTools();
  if(panel==='settings') buildSettings();
  if(panel==='console') buildConsole();
  if(panel==='help') buildHelp();
  if(panel==='about') buildAbout();
}
function renderUsbBody(){
  const st=S.status, j=S.job, busy=j&&j.running, isX=panel==='xbox';
  const u=$('#ubody'); if(!u) return;
  let h='';
  if(st.installed!=='1'){ h='<p>Set up Windows first, then come back here.</p>'; setHTML(u,h); setHTML($('#devlist'),''); setHTML($('#uact'),''); return; }
  if(st.usb_session==='1'){
    const o=st.usb_owner;
    const np=(st.usb_ports||'').trim().split(/\s+/).filter(Boolean).length;
    h+=`<p><b>${isX?'Controller session is running.':(np>1?np+' devices are attached to Windows.':'Your device is attached to Windows.')}</b></p>`;
    h+=`<p>${o.includes('usbfs')?'<span class="ok">✓ Windows has the device.</span>':o==='unplugged'?'<span class="warn">The device is unplugged. Plug it back in; it is added to Windows again by itself.</span>':'<span class="warn">Windows does not have the device yet.</span> Give it a few seconds.'}</p>`;
    if(isX) h+=`<ol class="how"><li>In Windows, double-click <b>Install Xbox Accessories</b> on the desktop (skip if it is already installed). The Microsoft Store opens: press <b>Get</b>. If it asks you to sign in you can cancel.</li><li>Open <b>Xbox Accessories</b> from the Start menu. If <b>Failed to sign in using Gaming Runtime Services</b> appears, press <b>Cancel</b> (not Install XBOX app). It can appear up to 3 times, and again as you move around the app: just cancel each time. Your controller should appear. If it does not, unplug the cable and plug it back in; DeckVM hands it back to Windows by itself.</li><li>Press the three dots (<b>More options</b>) under the controller, then <b>Update now</b>. <b>Do not touch the cable or the Deck's power button.</b> The controller restarts itself a few times. That is normal.</li><li>If it says 100% then "failed", wait a minute, then unplug and replug the cable. It should say it is up to date.</li><li>When done, press the button below.</li></ol>`;
    setHTML($('#devlist'),'');
    setHTML($('#uact'),`<p><button class="btn pri" data-act="stop" ${busy?'disabled':''}>${isX?'Finished: give the controller back to SteamOS':'Stop Windows and give the device back'}</button></p><p class="dim small">Your Deck password is only asked once, when the session starts. Afterwards unplug and replug the controller; it may need pairing again over Bluetooth.</p>`);
    setHTML(u,h); return;
  }
  if(isX){
    h+='<p>Update an Xbox controller\'s firmware without a Windows PC. You need a <b>USB data cable</b> (charge-only cables won\'t work) and batteries in the controller.</p>';
    h+='<p class="dim small">Windows takes the controller over for the update, so it is not usable in SteamOS meanwhile. You will be asked for your Deck password once, when the session starts (only this step needs it).</p>';
    if(st.edition!=='11'&&st.edition!=='tiny11') h+='<p class="warn small">Your Windows is '+esc(st.edition_name)+'. The Xbox Accessories app needs the Microsoft Store and a recent Windows, so it may not install here. Windows 11 Pro or Tiny11 are the best choices.</p>';
  } else h+='<p>Give any USB device to Windows. It disappears from SteamOS while Windows has it, and comes back when you stop. You\'ll be asked for your Deck password once. You can pick more than one.</p>';
  setHTML(u,h); renderDevList();
}
let selPorts=new Set(), selTouched=false;
function renderDevList(){
  const st=S.status, busy=S.job&&S.job.running, isX=panel==='xbox';
  if(st.usb_session==='1'||st.installed!=='1') return;
  const list=devList();
  for(const p of [...selPorts]) if(!list.find(d=>d.port===p)) selPorts.delete(p);
  if(!selTouched&&list.length===1) selPorts.add(list[0].port);
  const all=list.length>1&&list.every(d=>selPorts.has(d.port));
  let h=list.length?list.map(d=>{const on=selPorts.has(d.port);return `<div class="dev ${on?'on':''}" data-act="seldev" data-port="${esc(d.port)}" title="Click to choose or un-choose this device"><span class="n"><b>${esc(d.name)}</b><br><span class="dim small">${esc(d.id)} · port ${esc(d.port)}</span></span><span class="cb">${on?'☑':'☐'}</span></div>`}).join(''):`<p class="warn">${isX?'No Xbox controller found. Plug it in with a USB DATA cable.':'No external USB device found. Plug it in.'}</p>`;
  if(list.length>1) h+=`<p><button class="btn sm" data-act="selall" title="Choose every device in the list (up to 4)">${all?'Select none':'Select all'}</button></p>`;
  setHTML($('#devlist'),h);
  const n=selPorts.size;
  setHTML($('#uact'),`<div class="uactrow"><button class="btn pri" data-act="${isX?'xbox':'usb'}" ${(!n||busy)?'disabled':''}>${isX?'Start controller update session':(n>1?'Start Windows with these '+n+' devices':'Start Windows with this device')}</button><button class="btn" data-act="refresh" title="Look for devices again">Refresh</button></div>`);
}
async function loadDevices(){ if(panel!=='xbox'&&panel!=='usb') return; try{ devs=(await api('/api/devices')).devices; }catch(e){} renderDevList(); }

function buildTools(){
  $('#pb').innerHTML=`<h2>Shared folder</h2>
   <p class="dim small">A folder on your Deck that Windows sees as the Z: drive. Use it to move files in and out of Windows.</p>
   <p><button class="btn" data-act="openshared" title="Opens the folder in your file manager">Open the shared folder</button></p>
   <hr class="sep">
   <h2>Install disc (D: drive)</h2>
   <p class="dim small">While Windows installs, it keeps a small helper disc in the D: drive. If it is still there, this ejects it. Windows must be running.</p>
   <p><button class="btn" id="t-eject" data-act="eject" title="Ejects the install helper disc from the running Windows">⏏ Eject the install disc</button></p>
   <hr class="sep">
   <h2>Controller drivers</h2>
   <p class="dim small">If SteamOS's Xbox controller drivers were left switched off by an earlier USB session, this puts them back. It asks for your Deck password.</p>
   <p><button class="btn" id="t-repair" data-act="repair" title="Puts SteamOS's controller drivers back">Put the drivers back</button> <span class="dim small" id="t-rnote"></span></p>`;
  updateTools();
}
function updateTools(){
  if(!S) return;
  const st=S.status, busy=S.job&&S.job.running, run=st.vm==='running';
  const e=$('#t-eject'), r=$('#t-repair'), n=$('#t-rnote'); if(!e||!r) return;
  e.disabled=!(run&&!busy);
  const need=st.driver_block==='1'&&!run;
  r.disabled=!(need&&!busy);
  n.textContent=run?'Stop Windows first.':(need?'':'Nothing to put back.');
}
function buildSettings(){
  const st=S.status, inst=st.installed==='1', num=s=>parseInt(s)||0;
  $('#pb').innerHTML=`
   <div class="row"><label>Memory</label><input type="range" id="p-ram" min="3" max="10" value="${num(st.ram)}"><b id="pv-ram">${num(st.ram)} GB</b></div>
   <div class="row"><label>CPU cores</label><input type="range" id="p-cores" min="1" max="8" value="${num(st.cores)}"><b id="pv-cores">${num(st.cores)}</b></div>
   <div class="row"><label>Disk size</label><input type="range" id="p-disk" min="30" max="256" value="${num(st.disk)}" ${inst?'disabled':''}><b id="pv-disk">${num(st.disk)} GB</b></div>
   ${inst?'<div class="dim small">The disk size only applies to a new Windows.</div>':''}
   <div class="note" id="runnow" style="margin:0 0 6px"></div>
   <h2 style="margin-top:18px">Display</h2>
   <div class="row"><label style="min-width:0;width:auto"><input type="checkbox" id="p-touch" ${st.touch==='1'?'checked':''}> Touch display (experimental)</label></div>
   <div class="note" style="margin-left:26px">Tapping a text box opens Windows' touch keyboard. Needs a one-time download of about 100 MB. Not used during controller or USB sessions.</div>
   <h2 style="margin-top:18px">Advanced</h2>
   <details style="margin:8px 0 0 0"><summary class="dim small" style="cursor:pointer">USB recording (for troubleshooting)</summary>
    <div class="row"><label style="min-width:0;width:auto"><input type="checkbox" id="p-res" ${st.research==='1'?'checked':''}> Record the USB messages of the attached device (troubleshooting)</label></div>
    <div class="note" style="margin:0 0 8px 26px">Off by default. Only used when you attach a controller or other USB device to Windows. It saves the USB messages between Windows and that one device to a file in the logs folder on this Deck (<code>~/deckvm/logs</code>), so a failed controller update can be investigated. Other devices, your files, your screen and the internet are not recorded, and nothing is uploaded or sent anywhere. If the device is a keyboard, what you type on it would be in the file. It runs with the same password prompt as the USB session. You can delete the file at any time, or send it with a report if you choose to. Needs Stop and Start.</div>
   </details>
   <details style="margin:8px 0 0 0"><summary class="dim small" style="cursor:pointer">Custom options for Podman, the container and QEMU</summary>
    <div class="note" style="margin:6px 0">For people who know what these do. They are passed straight to Podman, the Windows container and QEMU. If Windows will not start with the Podman options, DeckVM starts it again without them. Needs Stop and Start.</div>
    <div class="row"><label style="min-width:0;width:130px">Podman options</label><input type="text" id="p-xpod" style="flex:1;min-width:0" placeholder="--cpu-shares 2048" value="${esc(st.x_podman||'')}"></div>
    <div class="row"><label style="min-width:0;width:130px">Container variables</label><input type="text" id="p-xenv" style="flex:1;min-width:0" placeholder="CPU_FLAGS=+topoext" value="${esc(st.x_env||'')}"></div>
    <div class="row"><label style="min-width:0;width:130px">QEMU options</label><input type="text" id="p-xqemu" style="flex:1;min-width:0" placeholder="-global kvm-pit.lost_tick_policy=delay" value="${esc(st.x_qemu||'')}"></div>
   </details>
   <p style="margin-top:18px"><button class="btn pri" data-act="savesettings">Save</button> <span class="dim small">${st.vm==='running'?'Memory and CPU changes need Stop and Start. The touch display switches straight away if it was on when Windows started.':'Applies the next time Windows starts.'}</span></p>
   <p><button class="btn sm" data-act="showpw">Show / hide the Windows password</button></p><div class="dim small" id="pwshow" style="user-select:text"></div>
   <div class="dz">
   <h2>⚠ Danger zone</h2>
   <h2 style="font-size:16px;margin-top:10px">Delete Windows</h2>
   <p class="dim small">Deletes the Windows disk (everything inside Windows) and keeps the VM software, so you can set up a different Windows.</p>
   <p><button class="btn bad" data-act="reset" ${inst?'':'disabled'}>Delete my Windows…</button></p>
   <h2 style="font-size:16px;margin-top:18px">Delete everything</h2>
   <p class="dim small">Deletes Windows, the VM software, your settings and logs, the desktop shortcut and DeckVM. SteamOS is untouched. Your latest report stays in your home folder.</p>
   <p><button class="btn bad" data-act="uninstall">Delete everything…</button></p>
   </div>`;
  for(const [id,suf] of [['ram',' GB'],['cores',''],['disk',' GB']]) $('#p-'+id).oninput=e=>{ $('#pv-'+id).textContent=e.target.value+suf; if(id==='ram') updateRunNow(); };
  updateRunNow();
}
/* What the running Windows really has, and a warning when the memory asked for is more than the Deck can spare. */
let runNowSince=0;
function updateRunNow(){
  const el=$('#runnow'); if(!el||!S) return;
  const st=S.status, f=x=>parseFloat(x)||0, run=st.vm==='running';
  let h='';
  if(!run) runNowSince=0;
  if(run){
    if(st.run_ram){
      const got=f(st.run_ram), asked=f(st.run_ram_asked), cores=st.run_cores||st.cores;
      h='<b>Running now:</b> '+st.run_ram+' GB memory, '+cores+' CPU cores'+''+'.';
      if(asked&&got<asked-0.3) h+=' You asked for '+asked+' GB, but Windows lowers its memory to what the Deck has free when it starts, so the Deck does not run out. Close other apps before starting, or ask for less.';
    } else {
      if(!runNowSince) runNowSince=Date.now();
      if(Date.now()-runNowSince<45000) h='<b>Running now:</b> checking the memory Windows started with…';   // after 45 seconds say nothing rather than show a line that never changes
    }
  } else {
    const free=f(st.mem_free_gb), want=+$('#p-ram').value;
    if(free&&want>free-1) h='The Deck has about '+free.toFixed(1)+' GB free right now. If you ask for nearly that much or more, Windows starts with less: it lowers its memory to what is free so the Deck does not run out.';
  }
  if(el.dataset.h!==h){ el.dataset.h=h; el.innerHTML=h; }
  el.style.display=h?'':'none';
}
function buildConsole(){
  $('#pb').innerHTML=`<div class="tabs"><button class="btn sm ${consoleTab==='job'?'on':''}" data-act="ctab" data-t="job">DeckVM</button><button class="btn sm ${consoleTab==='win'?'on':''}" data-act="ctab" data-t="win">Windows</button><button class="btn sm ${consoleTab==='rep'?'on':''}" data-act="ctab" data-t="rep">Report</button></div>
  <div><button class="btn sm" data-act="copylog">Copy</button> <button class="btn sm" data-act="report">Make a report</button></div><pre class="log" id="logpre"></pre>`;
  refreshConsole();
}
async function refreshConsole(){
  if(panel!=='console') return;
  const pre=$('#logpre'); if(!pre) return;
  if(!pre.__w){ pre.__w=1; pre.addEventListener('scroll',()=>{ pre.__near=pre.scrollHeight-pre.scrollTop-pre.clientHeight<40; }); }
  if(consoleTab==='job'){
    const r=await api('/api/log?from='+(logJob===(S.job&&S.job.id)?logFrom:0));
    if(logJob!==r.id){logJob=r.id;logLines=[];}
    else if(r.lines.length===0&&logFrom===0) {}
    logLines=logLines.concat(r.lines); logFrom=r.next;
    pre.textContent=logLines.join('\n')||'(nothing yet)';
  } else if(consoleTab==='win'){
    pre.textContent=(await api('/api/winlog')).lines.join('\n')||'(no Windows log yet)';
  } else {
    pre.textContent=reportText?('Saved at '+reportPath+'\n\n'+reportText):'No report yet. Press "Make a report".';
  }
  if(pre.__near!==false) pre.scrollTop=pre.scrollHeight;
}
async function loadReport(){
  const r=await api('/api/report'); reportText=r.text; reportPath=r.path; consoleTab='rep';
  openPanel('console');
  try{ await navigator.clipboard.writeText(reportText); notice('Report copied. It is also saved at '+reportPath+'. Paste it to NerdZap.','info'); }
  catch(e){ notice('Report ready in the Console. Press Copy, then send it to NerdZap.','info'); }
}
const L=(u,t)=>`<a href="${u}" target="_blank" rel="noopener noreferrer">${t}</a>`;
function buildAbout(){
  $('#pb').innerHTML=`<div class="about">
  <div class="big">NERD<i>ZAP</i></div>
  <div class="dim">DeckVM ${esc((S&&S.status.version)||'')} · built by ${L('https://nerdzap.com','NerdZap.com')}</div>
  <p>DeckVM runs Windows in a virtual machine on your Steam Deck, so you can do Windows-only jobs, like updating an Xbox controller's firmware, without a PC.</p>
  <p class="dim small">It is not made for games. Windows runs on emulated hardware with no access to the Deck's graphics chip, so busy graphics will feel slow.</p>
  <p><a class="ytbtn" href="https://www.youtube.com/@NerdZap?sub_confirmation=1" target="_blank" rel="noopener noreferrer">▶ Subscribe on YouTube</a></p>
  <h3>Support the project</h3>
  <p>DeckVM is free. If it helped you out in any way, a beer keeps the tools coming.<br>${L('https://www.buymeacoffee.com/nerdzap','🍺 Buy me a beer')}</p>
  <h3>More from NerdZap</h3>
  <ul>
   <li>${L('https://nerdzap.com/tools/deckzap/','DeckZap')}: add Xbox Cloud Gaming, GeForce Now, Netflix and more to your Steam library</li>
   <li>${L('https://nerdzap.com/free-games/','Free PC games')}: every free game on Steam, Epic, GOG and Prime Gaming</li>
   <li>${L('https://nerdzap.com/downloads/#windows-optimisation','Windows optimisation')}: the debloat scripts and handheld tweaks I use</li>
   <li>${L('https://nerdzap.com/status/','Game service status')}: is it down for everyone?</li>
   <li>${L('https://nerdzap.com','nerdzap.com')}: tech news, guides and tools</li>
  </ul>
  <h3>Follow NerdZap</h3>
  <p>${L('https://www.youtube.com/@NerdZap','YouTube')} · ${L('https://x.com/TheNerdZap','X (@TheNerdZap)')} · ${L('https://bsky.app/profile/nerdzap.com','Bluesky')} · ${L('https://instagram.com/thenerdzap','Instagram')} · ${L('https://facebook.com/nerdzap','Facebook')}</p>
  <h3>Open source credits</h3>
  <ul class="small">
   <li>${L('https://github.com/dockur/windows','dockur/windows')} (MIT): runs Windows in a container and downloads the version you pick</li>
   <li>${L('https://github.com/zedxter/xbox-firmware-linux','zedxter/xbox-firmware-linux')} (MIT, © 2026 zedxter): the udev relay and port-passthrough approach that keeps a controller attached while it restarts during an update</li>
   <li>${L('https://www.qemu.org','QEMU')} and Linux KVM: the virtual machine</li>
   <li>${L('https://podman.io','Podman')}: runs the container without needing administrator rights</li>
   <li>${L('https://novnc.com','noVNC')}: the Windows screen in this window</li>
   <li>Tiny11 and Tiny10 images (unofficial, by NTDEV), fetched by dockur when you pick them</li>
   <li>Python and bash, which this tool is made of</li>
  </ul>
  <h3>Disclaimer</h3>
  <p class="dim small">Provided as is, without warranty of any kind. Use at your own risk; NerdZap is not responsible for data loss. Windows is downloaded while you wait and is not included. Windows and Xbox are trademarks of Microsoft; DeckVM is not affiliated with or endorsed by Microsoft or Valve.</p>
  <p class="dim small">© 2026 NerdZap. All rights reserved.</p></div>`;
}
function buildHelp(){
  $('#pb').innerHTML=`<p><b>DeckVM ${esc(S.status.version||'')}</b></p>
  <p>Windows is in the middle, tools on the left. Your Deck password is only asked when you give a USB device (like a controller) to Windows.</p>
  <p><b>Windows screen is blank?</b> Press <b>⧉</b> at the top to open it in a separate browser tab, or wait a minute while Windows starts.</p>
  <p><b>Keyboard and mouse:</b> click inside the Windows screen to use it. Touch works as a mouse. To type by touch, switch on <b>Touch display (experimental)</b> in Settings: tapping a text box then opens Windows' touch keyboard. Or press <b>Steam + X</b> to open the Steam on-screen keyboard (Steam must be running).</p>
  <p><b>Not for gaming.</b> Windows runs on emulated hardware with no access to the Deck's graphics chip, so DeckVM suits tools and light apps, not games.</p>
  <p><b>Something went wrong?</b> Make a report and <a href="https://nerdzap.com/contact/" target="_blank" rel="noopener noreferrer">send it to NerdZap</a>.</p>
  <p><button class="btn" data-act="report">Make a report</button></p>
  <p>More help and videos: ${L('https://nerdzap.com','nerdzap.com')} · ${L('https://www.youtube.com/@NerdZap','YouTube')}</p>
  <p><button class="btn" data-act="quit">Close the DeckVM window server</button><br><span class="dim small">Windows keeps running if it is on. Open DeckVM again from the desktop shortcut.</span></p>`;
}

/* ---------- cancel dialog ---------- */
function closeModal(){ $('#modal').classList.remove('on'); }
function askCancel(){
  const j=S&&S.job; if(!j||!j.running) return;
  const st=S.status, p=S.progress||{};
  let t='Cancel?', b='', btns='';
  const back='<button class="btn" data-act="closemodal">No, keep going</button>';
  if((j.name==='auto')&&st.installed!=='1'){
    t='Cancel setting up Windows?';
    const got=(p.bytes>0)?' So far '+fmtB(p.bytes)+' of Windows has been downloaded.':'';
    b='DeckVM stops and tidies up.'+got+' You can keep what was downloaded, so the next try starts faster, or delete it and free the space.';
    btns='<button class="btn pri" data-act="docancel" data-keep="keep">Cancel and keep the download</button><button class="btn bad" data-act="docancel" data-keep="delete">Cancel and delete everything downloaded</button>'+back;
  } else if(['xbox','usb'].includes(j.name)){
    t='Cancel this USB session?';
    b="DeckVM stops Windows and gives your device and SteamOS's controller drivers back. Your Windows is kept.";
    btns='<button class="btn pri" data-act="docancel" data-keep="keep">Yes, cancel and put things back</button>'+back;
  } else if(j.name==='start'){
    t='Cancel starting Windows?'; b='Windows is stopped again. Your Windows and its files are kept.';
    btns='<button class="btn pri" data-act="docancel" data-keep="keep">Yes, cancel</button>'+back;
  } else if(j.name==='stop'){
    t='Switch Windows off now?'; b="Instead of waiting for Windows to shut down by itself, DeckVM switches it off straight away, like holding a PC's power button, and gives your controller back to SteamOS. Your Windows and its files are kept, but anything Windows had open and unsaved is lost.";
    btns='<button class="btn pri" data-act="docancel" data-keep="keep">Yes, switch it off now</button><button class="btn" data-act="closemodal">No, keep waiting</button>';
  } else if(j.name==='repair'){
    t='Cancel this?'; b='It is only part-way done. If you cancel, press Stop again afterwards to finish putting things back.';
    btns='<button class="btn pri" data-act="docancel" data-keep="keep">Yes, cancel</button>'+back;
  } else if(j.name==='reset'||j.name==='uninstall'){
    t='Cancel deleting?'; b='Anything already deleted stays deleted.';
    btns='<button class="btn pri" data-act="docancel" data-keep="keep">Yes, cancel</button>'+back;
  } else {
    t='Cancel '+(j.label||'this').toLowerCase()+'?'; btns='<button class="btn pri" data-act="docancel" data-keep="keep">Yes, cancel</button>'+back;
  }
  $('#m-t').textContent=t; $('#m-b').textContent=b; $('#m-btns').innerHTML=btns;
  $('#modal').classList.add('on');
}

/* ---------- actions ---------- */
async function act(a,d){
  switch(a){
    case 'panel': openPanel(d.p===panel&&d.p?'':d.p); break;
    case 'fullscreen': if(document.body.classList.contains('imm')) leaveFull(); else enterFull(); break;
    case 'unpop': if(BC) BC.postMessage('pop-close'); popAlive=0; setView(lastView||currentView()); break;
    case 'showpw': { const el=$('#pwshow'); if(el.dataset.on){ el.textContent=''; el.dataset.on=''; break; } try{ const r=await api('/api/winpass',{}); el.textContent=r.pw?('Windows user: '+r.user+'   password: '+r.pw):'No password found.'; el.dataset.on='1'; }catch(e){ el.textContent='Could not read it.'; } break; }
    case 'pick': winSel=d.w; buildEditions(); break;
    case 'setup': job({name:'setup',opts:{win:winSel,ram:+$('#s-ram').value,cores:+$('#s-cores').value,disk:+$('#s-disk').value,gpu:false,xboxapp:false}}); break;
    case 'start': clearNotice(); job({name:'start'}); break;
    case 'stop': if(confirm('Shut Windows down? Windows is asked to close properly (up to 2 minutes). Anything unsaved inside Windows is lost.')) job({name:'stop'}); break;
    case 'eject': job({name:'eject'}); break;
    case 'repair': clearNotice(); job({name:'repair'}); break;
    case 'openshared': { const r=await api('/api/open-shared',{}); notice((r.text||'Opened.').replace(/^\[ \w+ \]\s*/,''),'info'); curKey=null; break; }
    case 'cancel': askCancel(); break;
    case 'docancel': closeModal(); { const r=await api('/api/cancel',{keep:d.keep}); if(!r.ok) notice(r.error||'Could not cancel.','bad'); else notice('Cancelling…','info'); } poll(); break;
    case 'closemodal': closeModal(); break;
    case 'selall': { selTouched=true; const list=devList().slice(0,4); if(list.every(x=>selPorts.has(x.port))) selPorts.clear(); else list.forEach(x=>selPorts.add(x.port)); renderDevList(); break; }
    case 'pop': window.open('/?pop=1','deckvm-pop','popup=yes,width=1280,height=800'); break;
    case 'continue': api('/api/continue',{}); break;
    case 'skipreplug': api('/api/skipreplug',{}); break;
    case 'dismiss': dismissed=curKey||(S.job&&S.job.id); curKey=null; clearNotice(); break;
    case 'report': notice('Making a report…','info'); api('/api/job',{name:'report'}).then(()=>loadReport()).catch(()=>notice('The report could not be made. Run: bash ~/deckvm/deckvm.sh report','bad')); break;
    case 'seldev': selTouched=true; if(selPorts.has(d.port)) selPorts.delete(d.port); else if(selPorts.size<4) selPorts.add(d.port); renderDevList(); break;
    case 'refresh': loadDevices(); break;
    case 'xbox': openPanel(''); job({name:'xbox',ports:[...selPorts]}); break;
    case 'usb': openPanel(''); job({name:'usb',ports:[...selPorts]}); break;
    case 'ctab': consoleTab=d.t; logFrom=0; logLines=[]; logJob=null; buildConsole(); break;
    case 'copylog': try{ await navigator.clipboard.writeText($('#logpre').textContent); notice('Copied.','info');}catch(e){} break;
    case 'savesettings': {
      const o={ram:+$('#p-ram').value,cores:+$('#p-cores').value,research:$('#p-res').checked,touch:$('#p-touch').checked,extra_podman:$('#p-xpod').value,extra_env:$('#p-xenv').value,extra_qemu:$('#p-xqemu').value};
      if(!$('#p-disk').disabled) o.disk=+$('#p-disk').value;
      const old=S.status, running=old.vm==='running', num=x=>parseInt(x)||0;
      const touchChanged=o.touch!==(old.touch==='1');
      const needsRestart=running&&(num(old.ram)!==o.ram||num(old.cores)!==o.cores||(old.research==='1')!==o.research||(old.x_podman||'')!==o.extra_podman.trim()||(old.x_env||'')!==o.extra_env.trim()||(old.x_qemu||'')!==o.extra_qemu.trim()||(touchChanged&&o.touch&&old.touch_session!=='1'));
      const r=await job({name:'settings',opts:o});
      if(r.ok){
        let m='Saved.';
        if(needsRestart) m='Saved. Stop and start Windows to apply.';
        else if(running&&touchChanged) m=o.touch?'Saved. Switching to the touch display.':'Saved. Switching to the normal display.'+await pwSentence();
        notice(m,'info');
      }
      break; }
    case 'uninstall': if(confirm('Delete EVERYTHING: Windows, the VM software, settings and DeckVM itself? This cannot be undone.')) { openPanel(''); removing=true; job({name:'uninstall'}); } break;
    case 'reset': if(confirm('Delete your Windows and everything inside it? This cannot be undone.')) { openPanel(''); job({name:'reset'}); } break;
    case 'replace': if(confirm('Delete your current Windows and everything in it, then set up the new one?')) {
        const r=await job({name:'reset'}); if(r&&r.ok) pendingSetup=true; } break;
    case 'quit': if(confirm('Close the DeckVM window server? Windows keeps running if it is on.')) { await api('/api/quit',{}); document.body.innerHTML='<div style="padding:40px">DeckVM window closed. You can close this tab. Open DeckVM again from the desktop shortcut.</div>'; } break;
  }
}
let pendingSetup=false, lastAutoArgs=null, doneFor='';
document.addEventListener('click',e=>{const a=e.target.closest('[data-act]'); if(a) act(a.dataset.act,a.dataset);});

/* ---------- polling ---------- */
let polling=false;
async function poll(){
  if(polling) return; polling=true;
  try{
    S=await api('/api/state');
    if(POP){ if(S.status.vm!=='running'&&Date.now()>(window.__popT0||0)+8000) window.close(); setView('win'); failPolls=0; polling=false; return; }
    if(pendingSetup&&S.job&&!S.job.running&&S.job.name==='reset'&&S.job.rc===0){pendingSetup=false; if(lastAutoArgs){ job({name:'auto',args:lastAutoArgs}); } else { job({name:'setup',opts:{win:winSel,ram:+$('#s-ram').value,cores:+$('#s-cores').value,disk:+$('#s-disk').value,gpu:false,xboxapp:false}}); } }
    if(removing&&S.job&&S.job.name==='uninstall'&&!S.job.running){
      if(S.job.rc===0){ removing=false; api('/api/quit',{}).catch(()=>{}); document.body.innerHTML='<div style="padding:48px;max-width:640px;margin:auto"><div style="font:900 30px Arial Black,sans-serif;letter-spacing:-1px">NERD<span style="color:#f97316">ZAP</span></div><h2>DeckVM has been removed</h2><p>Windows, the VM software and your settings are gone and the space is free again. You can close this window.</p><p>Thanks for trying it. More at <a href="https://nerdzap.com">nerdzap.com</a>.</p></div>'; return; }
      removing=false;
    }
    render();
    if(panel==='console') refreshConsole();
    failPolls=0;
  }catch(e){
    failPolls++;
    if((e&&e.message==='forbidden')||failPolls>=8){ notice('DeckVM was restarted or closed. Close this window and open DeckVM again from its desktop shortcut.','bad'); $('#chiptxt').textContent='DeckVM is not running'; }
    else $('#chiptxt').textContent='Reconnecting to DeckVM…';
  }
  polling=false;
}
buildEditions();
/* The window icon sometimes shows a plain "W" until the page is reloaded. Asking for the icon again (no reload) sets it right. */
function refreshIcon(){ const l=document.querySelector('link[rel="icon"]'); if(l) l.href='/icon.png?'+Date.now(); }
window.addEventListener('load',()=>{ setTimeout(refreshIcon,1500); setTimeout(refreshIcon,8000); });
let tipTick=0; setInterval(()=>{ tipTick++; if(tipI<0||tipTick%11===0) nextTip(); },1000);   // the first tip shows as soon as the setup screen is up, then one every 11 seconds
(function(){ // Buy Me a Coffee: same black-counter fix as nerdzap.com, and a plain fallback when offline
  const i=$('#bmcimg'); const fb=()=>{const a=$('#bmc'); a.classList.add('fb'); a.textContent='🍺 Buy me a beer';};
  i.addEventListener('error',fb);
  if(window.fetch) fetch(i.src).then(r=>r.ok?r.text():Promise.reject()).then(t=>{const f=t.replace(/(<text x="226"[^>]*?)fill="white"/,'$1fill="#000"'); if(f!==t) i.src='data:image/svg+xml;charset=utf-8,'+encodeURIComponent(f);}).catch(()=>{});
})();
if(location.hash.startsWith('#p=')) setTimeout(()=>openPanel(location.hash.slice(3)),400);
window.__popT0=Date.now();
poll(); setInterval(poll,1500); if(!POP) setInterval(loadDevices,2500);
</script></body></html>
'''

if __name__ == "__main__":
    main()
GUIPY_EOF
  # The Guacamole client library for the touch display, as a plain readable file (Apache License 2.0, https://guacamole.apache.org/)
  cat > "$BASE/guacamole-common.js" <<'GUACJS_EOF'
/* Apache Guacamole guacamole-common-js 1.6.0. Copyright The Apache Software Foundation. Licensed under the Apache License, Version 2.0. https://guacamole.apache.org/ */
'use strict';var Guacamole=Guacamole||{};Guacamole.ArrayBufferReader=function(b){var a=this;b.onblob=function(b){if(Uint8Array.fromBase64){var c=Uint8Array.fromBase64(b);b=c.buffer}else{var d=window.atob(b);b=new ArrayBuffer(d.length);c=new Uint8Array(b);for(var f=0;f<d.length;f++)c[f]=d.charCodeAt(f)}if(a.ondata)a.ondata(b)};b.onend=function(){if(a.onend)a.onend()};this.onend=this.ondata=null};Guacamole=Guacamole||{};
Guacamole.ArrayBufferWriter=function(b){function a(a){for(var c="",d=0;d<a.byteLength;d++)c+=String.fromCharCode(a[d]);b.sendBlob(window.btoa(c))}var d=this;b.onack=function(a){if(d.onack)d.onack(a)};this.blobLength=Guacamole.ArrayBufferWriter.DEFAULT_BLOB_LENGTH;this.sendData=function(b){b=new Uint8Array(b);if(b.length<=d.blobLength)a(b);else for(var c=0;c<b.length;c+=d.blobLength)a(b.subarray(c,c+d.blobLength))};this.sendEnd=function(){b.sendEnd()};this.onack=null};
Guacamole.ArrayBufferWriter.DEFAULT_BLOB_LENGTH=6048;Guacamole=Guacamole||{};Guacamole.AudioContextFactory={singleton:null,getAudioContext:function(){var b=window.AudioContext||window.webkitAudioContext;if(b)try{return Guacamole.AudioContextFactory.singleton||(Guacamole.AudioContextFactory.singleton=new b),Guacamole.AudioContextFactory.singleton}catch(a){}return null}};Guacamole=Guacamole||{};Guacamole.AudioPlayer=function(){this.sync=function(){}};Guacamole.AudioPlayer.isSupportedType=function(b){return Guacamole.RawAudioPlayer.isSupportedType(b)};
Guacamole.AudioPlayer.getSupportedTypes=function(){return Guacamole.RawAudioPlayer.getSupportedTypes()};Guacamole.AudioPlayer.getInstance=function(b,a){return Guacamole.RawAudioPlayer.isSupportedType(a)?new Guacamole.RawAudioPlayer(b,a):null};
Guacamole.RawAudioPlayer=function(b,a){var d=Guacamole.RawAudioFormat.parse(a),c=Guacamole.AudioContextFactory.getAudioContext(),e=c.currentTime;b=new Guacamole.ArrayBufferReader(b);var f=1===d.bytesPerSample?window.Int8Array:window.Int16Array,h=1===d.bytesPerSample?128:32768,l=[],n=function(a){if(1>=a.length)return a[0];var b=0;a.forEach(function(a){b+=a.length});var c=0,d=new f(b);a.forEach(function(a){d.set(a,c);c+=a.length});return d};b.ondata=function(a){l.push(new f(new f(a)));if(a=n(l)){var b=
Number.MAX_VALUE,k=a.length,r=Math.floor(.02*d.rate);for(r=Math.max(d.channels*r,d.channels*(Math.floor(a.length/d.channels)-r));r<a.length;r+=d.channels){for(var q=0,v=0;v<d.channels;v++)q+=Math.abs(a[r+v]);q<=b&&(k=r+d.channels,b=q)}l=k===a.length?[a]:[new f(a.buffer.slice(0,k*d.bytesPerSample)),new f(a.buffer.slice(k*d.bytesPerSample))];a=l.shift()}else a=null;if(a){b=c.currentTime;e<b&&(e=b);b=c.createBufferSource();b.connect(c.destination);b.start||(b.start=b.noteOn);k=a;r=k.length/d.channels;
q=c.currentTime;e<q&&(e=q);q=c.createBuffer(d.channels,r,d.rate);for(v=0;v<d.channels;v++)for(var m=q.getChannelData(v),t=v,y=0;y<r;y++)m[y]=k[t]/h,t+=d.channels;b.buffer=q;b.start(e);e+=a.length/d.channels/d.rate}};this.sync=function(){e=Math.min(e,c.currentTime+.3)}};Guacamole.RawAudioPlayer.prototype=new Guacamole.AudioPlayer;Guacamole.RawAudioPlayer.isSupportedType=function(b){return Guacamole.AudioContextFactory.getAudioContext()?null!==Guacamole.RawAudioFormat.parse(b):!1};
Guacamole.RawAudioPlayer.getSupportedTypes=function(){return Guacamole.AudioContextFactory.getAudioContext()?["audio/L8","audio/L16"]:[]};Guacamole=Guacamole||{};Guacamole.AudioRecorder=function(){this.onerror=this.onclose=null};Guacamole.AudioRecorder.isSupportedType=function(b){return Guacamole.RawAudioRecorder.isSupportedType(b)};Guacamole.AudioRecorder.getSupportedTypes=function(){return Guacamole.RawAudioRecorder.getSupportedTypes()};
Guacamole.AudioRecorder.getInstance=function(b,a){return Guacamole.RawAudioRecorder.isSupportedType(a)?new Guacamole.RawAudioRecorder(b,a):null};
Guacamole.RawAudioRecorder=function(b,a){var d=this,c=Guacamole.RawAudioFormat.parse(a),e=Guacamole.AudioContextFactory.getAudioContext();navigator.mediaDevices||(navigator.mediaDevices={});navigator.mediaDevices.getUserMedia||(navigator.mediaDevices.getUserMedia=(navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia).bind(navigator));var f=new Guacamole.ArrayBufferWriter(b),h=1===c.bytesPerSample?window.Int8Array:window.Int16Array,l=1===c.bytesPerSample?
128:32768,n=0,m=0,g=null,k=null,r=null,q=function(a){if(0===a)return 1;a*=Math.PI;return Math.sin(a)/a},v=function(a){n+=a.length;var b=Math.round(n*c.rate/a.sampleRate)-m;m+=b;for(var d=new h(b*c.channels),e=0;e<c.channels;e++)for(var f=a.getChannelData(e),t=e,p=0;p<b;p++){for(var w=t,g=f,k=p/(b-1)*(g.length-1),E=Math.floor(k)+3,y=0,v=Math.floor(k)-3+1;v<=E;v++){var r=g[v]||0;var x=k-v;x=-3<x&&3>x?q(x)*q(x/3):0;y+=r*x}d[w]=y*l;t+=c.channels}return d},x=function(a){r=e.createScriptProcessor(2048,
c.channels,c.channels);r.connect(e.destination);r.onaudioprocess=function(a){f.sendData(v(a.inputBuffer).buffer)};k=e.createMediaStreamSource(a);k.connect(r);"suspended"===e.state&&e.resume();g=a},t=function(){f.sendEnd();if(d.onerror)d.onerror()};f.onack=function(a){if(a.code!==Guacamole.Status.Code.SUCCESS||g){k&&k.disconnect();r&&r.disconnect();if(g)for(var b=g.getTracks(),c=0;c<b.length;c++)b[c].stop();g=k=r=null;f.sendEnd();f.onack=null;if(a.code===Guacamole.Status.Code.RESOURCE_CLOSED){if(d.onclose)d.onclose()}else if(d.onerror)d.onerror()}else(a=
navigator.mediaDevices.getUserMedia({audio:!0},x,t))&&a.then&&a.then(x,t)}};Guacamole.RawAudioRecorder.prototype=new Guacamole.AudioRecorder;Guacamole.RawAudioRecorder.isSupportedType=function(b){return Guacamole.AudioContextFactory.getAudioContext()?null!==Guacamole.RawAudioFormat.parse(b):!1};Guacamole.RawAudioRecorder.getSupportedTypes=function(){return Guacamole.AudioContextFactory.getAudioContext()?["audio/L8","audio/L16"]:[]};Guacamole=Guacamole||{};
Guacamole.BlobReader=function(b,a){var d=this,c=0;var e=window.BlobBuilder?new BlobBuilder:window.WebKitBlobBuilder?new WebKitBlobBuilder:window.MozBlobBuilder?new MozBlobBuilder:new function(){var b=[];this.append=function(c){b.push(new Blob([c],{type:a}))};this.getBlob=function(){return new Blob(b,{type:a})}};b.onblob=function(a){a=window.atob(a);for(var f=new ArrayBuffer(a.length),l=new Uint8Array(f),n=0;n<a.length;n++)l[n]=a.charCodeAt(n);e.append(f);c+=f.byteLength;if(d.onprogress)d.onprogress(f.byteLength);
b.sendAck("OK",0)};b.onend=function(){if(d.onend)d.onend()};this.getLength=function(){return c};this.getBlob=function(){return e.getBlob()};this.onend=this.onprogress=null};Guacamole=Guacamole||{};
Guacamole.BlobWriter=function(b){var a=this,d=new Guacamole.ArrayBufferWriter(b);d.onack=function(b){if(a.onack)a.onack(b)};this.sendBlob=function(b){var c=0,f=new FileReader,h=function(){if(c>=b.size){if(a.oncomplete)a.oncomplete(b)}else{a:{var e=c;var h=c+d.blobLength,m=(b.slice||b.webkitSlice||b.mozSlice).bind(b),g=h-e;if(g!==h){var k=m(e,g);if(k.size===g){e=k;break a}}e=m(e,h)}c+=d.blobLength;f.readAsArrayBuffer(e)}};f.onload=function(){d.sendData(f.result);d.onack=function(e){if(a.onack)a.onack(e);
if(!e.isError()){if(a.onprogress)a.onprogress(b,c-d.blobLength);h()}}};f.onerror=function(){if(a.onerror)a.onerror(b,c,f.error)};h()};this.sendEnd=function(){d.sendEnd()};this.oncomplete=this.onprogress=this.onerror=this.onack=null};Guacamole=Guacamole||{};
Guacamole.Client=function(b){function a(a){if(a!=e&&(e=a,c.onstatechange))c.onstatechange(e)}function d(){return e==Guacamole.Client.State.CONNECTED||e==Guacamole.Client.State.WAITING}var c=this,e=Guacamole.Client.State.IDLE,f=0,h=null,l=0,n={0:"butt",1:"round",2:"square"},m={0:"bevel",1:"miter",2:"round"},g=new Guacamole.Display,k={},r={},q=[],v=[],x=[],t=new Guacamole.IntegerPool,y=[];this.exportState=function(a){var p={currentState:e,currentTimestamp:f,layers:{}},b={},c;for(c in k)b[c]=k[c];g.flush(function(){for(var c in b){var d=
parseInt(c),e=b[c],w=e.toCanvas(),f={width:e.width,height:e.height};e.width&&e.height&&(f.url=w.toDataURL("image/png"));if(0<d){f.x=e.x;f.y=e.y;f.z=e.z;f.alpha=e.alpha;f.matrix=e.matrix;d=f;a:{w=void 0;if(e=e.parent)for(w in k)if(e===k[w]){e=parseInt(w);break a}e=null}d.parent=e}p.layers[c]=f}a(p)})};this.importState=function(a,b){var p;e=a.currentState;f=a.currentTimestamp;g.cancel();for(p in k){var c=parseInt(p);0<c&&k[p].dispose()}k={};for(p in a.layers){c=parseInt(p);var d=a.layers[p],w=u(c);
g.resize(w,d.width,d.height);d.url&&(g.setChannelMask(w,Guacamole.Layer.SRC),g.draw(w,0,0,d.url));0<c&&0<=d.parent&&(c=u(d.parent),g.move(w,c,d.x,d.y,d.z),g.shade(w,d.alpha),d=d.matrix,g.distort(w,d[0],d[1],d[2],d[3],d[4],d[5]))}g.flush(b)};this.getDisplay=function(){return g};this.sendSize=function(a,c){d()&&b.sendMessage("size",a,c)};this.sendKeyEvent=function(a,c){d()&&b.sendMessage("key",c,a)};this.sendMouseState=function(a,c){if(d()){var p=a.x,e=a.y;c&&(p/=g.getScale(),e/=g.getScale());g.moveCursor(Math.floor(p),
Math.floor(e));c=0;a.left&&(c|=1);a.middle&&(c|=2);a.right&&(c|=4);a.up&&(c|=8);a.down&&(c|=16);b.sendMessage("mouse",Math.floor(p),Math.floor(e),c)}};this.sendTouchState=function(a,c){if(d()){var p=a.x,e=a.y;c&&(p/=g.getScale(),e/=g.getScale());b.sendMessage("touch",a.id,Math.floor(p),Math.floor(e),Math.floor(a.radiusX),Math.floor(a.radiusY),a.angle,a.force)}};this.createOutputStream=function(){var a=t.next();return y[a]=new Guacamole.OutputStream(c,a)};this.createAudioStream=function(a){var p=c.createOutputStream();
b.sendMessage("audio",p.index,a);return p};this.createFileStream=function(a,d){var p=c.createOutputStream();b.sendMessage("file",p.index,a,d);return p};this.createPipeStream=function(a,d){var p=c.createOutputStream();b.sendMessage("pipe",p.index,a,d);return p};this.createClipboardStream=function(a){var p=c.createOutputStream();b.sendMessage("clipboard",p.index,a);return p};this.createArgumentValueStream=function(a,d){var p=c.createOutputStream();b.sendMessage("argv",p.index,a,d);return p};this.createObjectOutputStream=
function(a,d,e){var p=c.createOutputStream();b.sendMessage("put",a,p.index,d,e);return p};this.requestObjectInputStream=function(a,c){d()&&b.sendMessage("get",a,c)};this.sendAck=function(a,c,e){d()&&b.sendMessage("ack",a,c,e)};this.sendBlob=function(a,c){d()&&b.sendMessage("blob",a,c)};this.endStream=function(a){d()&&(b.sendMessage("end",a),y[a]&&(t.free(a),delete y[a]))};this.onsync=this.onrequired=this.onpipe=this.onfilesystem=this.onfile=this.onclipboard=this.onargv=this.onmultitouch=this.onvideo=
this.onaudio=this.onleave=this.onjoin=this.onmsg=this.onerror=this.onname=this.onstatechange=null;var u=function(a){var b=k[a];b||(b=0===a?g.getDefaultLayer():0<a?g.createLayer():g.createBuffer(),k[a]=b);return b},C={"miter-limit":function(a,b){g.setMiterLimit(a,parseFloat(b))},"multi-touch":function(a,b){if(c.onmultitouch&&a instanceof Guacamole.Display.VisibleLayer)c.onmultitouch(a,parseInt(b))}},D={ack:function(a){var b=parseInt(a[0]),p=a[1];a=parseInt(a[2]);var c=y[b];if(c){if(c.onack)c.onack(new Guacamole.Status(a,
p));256<=a&&y[b]===c&&(t.free(b),delete y[b])}},arc:function(a){var b=u(parseInt(a[0])),p=parseInt(a[1]),c=parseInt(a[2]),d=parseInt(a[3]),e=parseFloat(a[4]),f=parseFloat(a[5]);a=parseInt(a[6]);g.arc(b,p,c,d,e,f,0!=a)},argv:function(a){var b=parseInt(a[0]),p=a[1];a=a[2];c.onargv?(b=v[b]=new Guacamole.InputStream(c,b),c.onargv(b,p,a)):c.sendAck(b,"Receiving argument values unsupported",256)},audio:function(a){var b=parseInt(a[0]);a=a[1];var p=v[b]=new Guacamole.InputStream(c,b),d=null;c.onaudio&&(d=
c.onaudio(p,a));d||(d=Guacamole.AudioPlayer.getInstance(p,a));d?(r[b]=d,c.sendAck(b,"OK",0)):c.sendAck(b,"BAD TYPE",783)},blob:function(a){var b=parseInt(a[0]);a=a[1];if((b=v[b])&&b.onblob)b.onblob(a)},body:function(a){var b=parseInt(a[0]);b=x[b];var p=parseInt(a[1]),d=a[2];a=a[3];b&&b.onbody?(p=v[p]=new Guacamole.InputStream(c,p),b.onbody(p,d,a)):c.sendAck(p,"Receipt of body unsupported",256)},cfill:function(a){var b=parseInt(a[0]),p=u(parseInt(a[1])),c=parseInt(a[2]),d=parseInt(a[3]),e=parseInt(a[4]);
a=parseInt(a[5]);g.setChannelMask(p,b);g.fillColor(p,c,d,e,a)},clip:function(a){a=u(parseInt(a[0]));g.clip(a)},clipboard:function(a){var b=parseInt(a[0]);a=a[1];c.onclipboard?(b=v[b]=new Guacamole.InputStream(c,b),c.onclipboard(b,a)):c.sendAck(b,"Clipboard unsupported",256)},close:function(a){a=u(parseInt(a[0]));g.close(a)},copy:function(a){var b=u(parseInt(a[0])),c=parseInt(a[1]),p=parseInt(a[2]),d=parseInt(a[3]),e=parseInt(a[4]),f=parseInt(a[5]),t=u(parseInt(a[6])),k=parseInt(a[7]);a=parseInt(a[8]);
g.setChannelMask(t,f);g.copy(b,c,p,d,e,t,k,a)},cstroke:function(a){var b=parseInt(a[0]),c=u(parseInt(a[1])),d=n[parseInt(a[2])],p=m[parseInt(a[3])],e=parseInt(a[4]),f=parseInt(a[5]),t=parseInt(a[6]),k=parseInt(a[7]);a=parseInt(a[8]);g.setChannelMask(c,b);g.strokeColor(c,d,p,e,f,t,k,a)},cursor:function(a){var b=parseInt(a[0]),c=parseInt(a[1]),d=u(parseInt(a[2])),p=parseInt(a[3]),e=parseInt(a[4]),f=parseInt(a[5]);a=parseInt(a[6]);g.setCursor(b,c,d,p,e,f,a)},curve:function(a){var b=u(parseInt(a[0])),
c=parseInt(a[1]),d=parseInt(a[2]),p=parseInt(a[3]),e=parseInt(a[4]),f=parseInt(a[5]);a=parseInt(a[6]);g.curveTo(b,c,d,p,e,f,a)},disconnect:function(a){c.disconnect()},dispose:function(a){a=parseInt(a[0]);if(0<a){var b=u(a);g.dispose(b);delete k[a]}else 0>a&&delete k[a]},distort:function(a){var b=parseInt(a[0]),c=parseFloat(a[1]),d=parseFloat(a[2]),e=parseFloat(a[3]),p=parseFloat(a[4]),f=parseFloat(a[5]);a=parseFloat(a[6]);0<=b&&(b=u(b),g.distort(b,c,d,e,p,f,a))},error:function(a){var b=a[0];a=parseInt(a[1]);
if(c.onerror)c.onerror(new Guacamole.Status(a,b));c.disconnect()},end:function(a){a=parseInt(a[0]);var b=v[a];if(b){if(b.onend)b.onend();delete v[a]}},file:function(a){var b=parseInt(a[0]),d=a[1];a=a[2];c.onfile?(b=v[b]=new Guacamole.InputStream(c,b),c.onfile(b,d,a)):c.sendAck(b,"File transfer unsupported",256)},filesystem:function(a){var b=parseInt(a[0]);a=a[1];c.onfilesystem&&(b=x[b]=new Guacamole.Object(c,b),c.onfilesystem(b,a))},identity:function(a){a=u(parseInt(a[0]));g.setTransform(a,1,0,0,
1,0,0)},img:function(a){var b=parseInt(a[0]),d=parseInt(a[1]),e=u(parseInt(a[2])),p=a[3],f=parseInt(a[4]);a=parseInt(a[5]);b=v[b]=new Guacamole.InputStream(c,b);g.setChannelMask(e,d);g.drawStream(e,f,a,b,p)},jpeg:function(a){var b=parseInt(a[0]),c=u(parseInt(a[1])),d=parseInt(a[2]),e=parseInt(a[3]);a=a[4];g.setChannelMask(c,b);g.draw(c,d,e,"data:image/jpeg;base64,"+a)},lfill:function(a){var b=parseInt(a[0]),c=u(parseInt(a[1]));a=u(parseInt(a[2]));g.setChannelMask(c,b);g.fillLayer(c,a)},line:function(a){var b=
u(parseInt(a[0])),c=parseInt(a[1]);a=parseInt(a[2]);g.lineTo(b,c,a)},lstroke:function(a){var b=parseInt(a[0]),c=u(parseInt(a[1]));a=u(parseInt(a[2]));g.setChannelMask(c,b);g.strokeLayer(c,a)},mouse:function(a){var b=parseInt(a[0]);a=parseInt(a[1]);g.showCursor(!0);g.moveCursor(b,a)},move:function(a){var b=parseInt(a[0]),c=parseInt(a[1]),d=parseInt(a[2]),e=parseInt(a[3]);a=parseInt(a[4]);0<b&&0<=c&&(b=u(b),c=u(c),g.move(b,c,d,e,a))},msg:function(a){var b=!0;var d=parseInt(a[0]);c.onmsg&&(b=c.onmsg(d,
a.slice(1)),void 0===b&&(b=!0));if(b)switch(d){case Guacamole.Client.Message.USER_JOINED:b=a[1];a=a[2];if(c.onjoin)c.onjoin(b,a);break;case Guacamole.Client.Message.USER_LEFT:if(b=a[1],a=a[2],c.onleave)c.onleave(b,a)}},name:function(a){if(c.onname)c.onname(a[0])},nest:function(a){var c=parseInt(a[0]),d=q[c];null==d&&(d=q[c]=new Guacamole.Parser,d.oninstruction=b.oninstruction);d.receive(a[1])},pipe:function(a){var b=parseInt(a[0]),d=a[1];a=a[2];c.onpipe?(b=v[b]=new Guacamole.InputStream(c,b),c.onpipe(b,
d,a)):c.sendAck(b,"Named pipes unsupported",256)},png:function(a){var b=parseInt(a[0]),c=u(parseInt(a[1])),d=parseInt(a[2]),e=parseInt(a[3]);a=a[4];g.setChannelMask(c,b);g.draw(c,d,e,"data:image/png;base64,"+a)},pop:function(a){a=u(parseInt(a[0]));g.pop(a)},push:function(a){a=u(parseInt(a[0]));g.push(a)},rect:function(a){var b=u(parseInt(a[0])),c=parseInt(a[1]),d=parseInt(a[2]),e=parseInt(a[3]);a=parseInt(a[4]);g.rect(b,c,d,e,a)},required:function(a){if(c.onrequired)c.onrequired(a)},reset:function(a){a=
u(parseInt(a[0]));g.reset(a)},set:function(a){var b=u(parseInt(a[0])),c=a[2];(a=C[a[1]])&&a(b,c)},shade:function(a){var b=parseInt(a[0]);a=parseInt(a[1]);0<=b&&(b=u(b),g.shade(b,a))},size:function(a){var b=parseInt(a[0]);b=u(b);var c=parseInt(a[1]);a=parseInt(a[2]);g.resize(b,c,a)},start:function(a){var b=u(parseInt(a[0])),c=parseInt(a[1]);a=parseInt(a[2]);g.moveTo(b,c,a)},sync:function(d){var t=parseInt(d[0]);d=d[1]?parseInt(d[1]):0;g.flush(function(){for(var a in r){var c=r[a];c&&c.sync()}t!==f&&
(b.sendMessage("sync",t),f=t)},t,d);e===Guacamole.Client.State.WAITING&&a(Guacamole.Client.State.CONNECTED);if(c.onsync)c.onsync(t,d)},transfer:function(a){var b=u(parseInt(a[0])),c=parseInt(a[1]),d=parseInt(a[2]),e=parseInt(a[3]),f=parseInt(a[4]),t=parseInt(a[5]),k=u(parseInt(a[6])),h=parseInt(a[7]);a=parseInt(a[8]);3===t?g.put(b,c,d,e,f,k,h,a):5!==t&&g.transfer(b,c,d,e,f,k,h,a,Guacamole.Client.DefaultTransferFunction[t])},transform:function(a){var b=u(parseInt(a[0])),c=parseFloat(a[1]),d=parseFloat(a[2]),
e=parseFloat(a[3]),f=parseFloat(a[4]),t=parseFloat(a[5]);a=parseFloat(a[6]);g.transform(b,c,d,e,f,t,a)},undefine:function(a){a=parseInt(a[0]);if((a=x[a])&&a.onundefine)a.onundefine()},video:function(a){var b=parseInt(a[0]),d=u(parseInt(a[1]));a=a[2];var e=v[b]=new Guacamole.InputStream(c,b),f=null;c.onvideo&&(f=c.onvideo(e,d,a));f||(f=Guacamole.VideoPlayer.getInstance(e,d,a));f?c.sendAck(b,"OK",0):c.sendAck(b,"BAD TYPE",783)}},A=function(){b.sendMessage("nop");l=(new Date).getTime()},B=function(){window.clearTimeout(h);
var a=(new Date).getTime();a=Math.max(l+5E3-a,0);0<a?h=window.setTimeout(A,a):A()};b.oninstruction=function(a,b){(a=D[a])&&a(b);B()};this.disconnect=function(){e!=Guacamole.Client.State.DISCONNECTED&&e!=Guacamole.Client.State.DISCONNECTING&&(a(Guacamole.Client.State.DISCONNECTING),window.clearTimeout(h),b.sendMessage("disconnect"),b.disconnect(),a(Guacamole.Client.State.DISCONNECTED))};this.connect=function(c){a(Guacamole.Client.State.CONNECTING);try{b.connect(c)}catch(w){throw a(Guacamole.Client.State.IDLE),
w;}B();a(Guacamole.Client.State.WAITING)}};Guacamole.Client.State={IDLE:0,CONNECTING:1,WAITING:2,CONNECTED:3,DISCONNECTING:4,DISCONNECTED:5};
Guacamole.Client.DefaultTransferFunction={0:function(b,a){a.red=a.green=a.blue=0},15:function(b,a){a.red=a.green=a.blue=255},3:function(b,a){a.red=b.red;a.green=b.green;a.blue=b.blue;a.alpha=b.alpha},5:function(b,a){},12:function(b,a){a.red=255&~b.red;a.green=255&~b.green;a.blue=255&~b.blue;a.alpha=b.alpha},10:function(b,a){a.red=255&~a.red;a.green=255&~a.green;a.blue=255&~a.blue},1:function(b,a){a.red&=b.red;a.green&=b.green;a.blue&=b.blue},14:function(b,a){a.red=255&~(b.red&a.red);a.green=255&~(b.green&
a.green);a.blue=255&~(b.blue&a.blue)},7:function(b,a){a.red|=b.red;a.green|=b.green;a.blue|=b.blue},8:function(b,a){a.red=255&~(b.red|a.red);a.green=255&~(b.green|a.green);a.blue=255&~(b.blue|a.blue)},6:function(b,a){a.red^=b.red;a.green^=b.green;a.blue^=b.blue},9:function(b,a){a.red=255&~(b.red^a.red);a.green=255&~(b.green^a.green);a.blue=255&~(b.blue^a.blue)},4:function(b,a){a.red&=255&~b.red;a.green&=255&~b.green;a.blue&=255&~b.blue},13:function(b,a){a.red=255&(~b.red|a.red);a.green=255&(~b.green|
a.green);a.blue=255&(~b.blue|a.blue)},2:function(b,a){a.red=255&b.red&~a.red;a.green=255&b.green&~a.green;a.blue=255&b.blue&~a.blue},11:function(b,a){a.red=255&(b.red|~a.red);a.green=255&(b.green|~a.green);a.blue=255&(b.blue|~a.blue)}};Guacamole.Client.Message={USER_JOINED:1,USER_LEFT:2};Guacamole=Guacamole||{};Guacamole.DataURIReader=function(b,a){var d=this,c="data:"+a+";base64,";b.onblob=function(a){c+=a};b.onend=function(){if(d.onend)d.onend()};this.getURI=function(){return c};this.onend=null};
Guacamole=Guacamole||{};
Guacamole.Display=function(){function b(a,b){var c=this;this.blocked=b;this.cancel=function(){c.blocked=!1;a=null};this.unblock=function(){c.blocked&&(c.blocked=!1,k.length&&r())};this.execute=function(){a&&a()}}function a(a,c){a=new b(a,c);g.push(a);return a}var d=this,c=0,e=0,f=1,h=document.createElement("div");h.style.position="relative";h.style.width=c+"px";h.style.height=e+"px";h.style.transformOrigin=h.style.webkitTransformOrigin=h.style.MozTransformOrigin=h.style.OTransformOrigin=h.style.msTransformOrigin=
"0 0";var l=new Guacamole.Display.VisibleLayer(c,e),n=new Guacamole.Display.VisibleLayer(0,0);n.setChannelMask(Guacamole.Layer.SRC);h.appendChild(l.getElement());h.appendChild(n.getElement());var m=document.createElement("div");m.style.position="relative";m.style.width=c*f+"px";m.style.height=e*f+"px";m.appendChild(h);this.statisticWindow=this.cursorY=this.cursorX=this.cursorHotspotY=this.cursorHotspotX=0;this.onstatistics=this.oncursor=this.onresize=null;var g=[],k=[],r=function(){for(var a=0,b=
0,c=0,d=0;d<k.length;){var e=k[d];if(!e.isReady())break;e.flush();a=e.localTimestamp;b=e.remoteTimestamp;c+=e.logicalFrames;d++}k.splice(0,d);d&&v(a,b,c)},q=[],v=function(a,b,c){if(d.statisticWindow){for(var e=(new Date).getTime(),f=0;f<q.length&&!(e-q[f].timestamp<=d.statisticWindow);f++);q.splice(0,f-1);q.push({localTimestamp:a,remoteTimestamp:b,timestamp:e,frames:c});b=(q[q.length-1].timestamp-q[0].timestamp)/1E3;c=(q[q.length-1].remoteTimestamp-q[0].remoteTimestamp)/1E3;f=q.length;var t=q.reduce(function(a,
b){return a+b.frames},0),g=q.reduce(function(a,b){return a+Math.max(0,b.frames-1)},0);a=new Guacamole.Display.Statistics({processingLag:e-a,desktopFps:c&&t?t/c:null,clientFps:b?f/b:null,serverFps:c?f/c:null,dropRate:c?g/c:null});if(d.onstatistics)d.onstatistics(a)}},x=function(a,b,c,d){this.localTimestamp=(new Date).getTime();this.remoteTimestamp=c||this.localTimestamp;this.logicalFrames=d||0;this.cancel=function(){a=null;b.forEach(function(a){a.cancel()});b=[]};this.isReady=function(){for(var a=
0;a<b.length;a++)if(b[a].blocked)return!1;return!0};this.flush=function(){for(var c=0;c<b.length;c++)b[c].execute();a&&a()}};this.getElement=function(){return m};this.getWidth=function(){return c};this.getHeight=function(){return e};this.getDefaultLayer=function(){return l};this.getCursorLayer=function(){return n};this.createLayer=function(){var a=new Guacamole.Display.VisibleLayer(c,e);a.move(l,0,0,0);return a};this.createBuffer=function(){var a=new Guacamole.Layer(0,0);a.autosize=1;return a};this.flush=
function(a,b,c){k.push(new x(a,g,b,c));g=[];r()};this.cancel=function(){k.forEach(function(a){a.cancel()});k=[];g.forEach(function(a){a.cancel()});g=[]};this.setCursor=function(b,c,e,f,g,k,h){a(function(){d.cursorHotspotX=b;d.cursorHotspotY=c;n.resize(k,h);n.copy(e,f,g,k,h,0,0);d.moveCursor(d.cursorX,d.cursorY);if(d.oncursor)d.oncursor(n.toCanvas(),b,c)})};this.showCursor=function(a){var b=n.getElement(),c=b.parentNode;!1===a?c&&c.removeChild(b):c!==h&&h.appendChild(b)};this.moveCursor=function(a,
b){n.translate(a-d.cursorHotspotX,b-d.cursorHotspotY);d.cursorX=a;d.cursorY=b};this.resize=function(b,g,k){a(function(){b.resize(g,k);if(b===l&&(c=g,e=k,h.style.width=c+"px",h.style.height=e+"px",m.style.width=c*f+"px",m.style.height=e*f+"px",d.onresize))d.onresize(g,k)})};this.drawImage=function(b,c,d,e){a(function(){b.drawImage(c,d,e)})};this.drawBlob=function(b,c,d,e){if(window.createImageBitmap){var f;var g=a(function(){b.drawImage(c,d,f)},!0);window.createImageBitmap(e).then(function(a){f=a;
g.unblock()})}else{var k=URL.createObjectURL(e);g=a(function(){h.width&&h.height&&b.drawImage(c,d,h);URL.revokeObjectURL(k)},!0);var h=new Image;h.onload=g.unblock;h.onerror=g.unblock;h.src=k}};this.drawStream=function(b,c,e,f,g){if(window.ImageDecoder&&window.ReadableStream){f=new ImageDecoder({type:g,data:f.toReadableStream()});var k=null,h=a(function(){b.drawImage(c,e,k)},!0);f.decode({completeFramesOnly:!0}).then(function(a){k=a.image;h.unblock()})}else{var t=new Guacamole.DataURIReader(f,g);
t.onend=function(){d.draw(b,c,e,t.getURI())}}};this.draw=function(b,c,d,e){var f=a(function(){g.width&&g.height&&b.drawImage(c,d,g)},!0),g=new Image;g.onload=f.unblock;g.onerror=f.unblock;g.src=e};this.play=function(b,c,d,e){var f=document.createElement("video");f.type=c;f.src=e;f.addEventListener("play",function(){function a(){b.drawImage(0,0,f);f.ended||window.setTimeout(a,20)}a()},!1);a(f.play)};this.transfer=function(b,c,d,e,f,g,k,h,n){a(function(){g.transfer(b,c,d,e,f,k,h,n)})};this.put=function(b,
c,d,e,f,g,k,h){a(function(){g.put(b,c,d,e,f,k,h)})};this.copy=function(b,c,d,e,f,g,k,h){a(function(){g.copy(b,c,d,e,f,k,h)})};this.moveTo=function(b,c,d){a(function(){b.moveTo(c,d)})};this.lineTo=function(b,c,d){a(function(){b.lineTo(c,d)})};this.arc=function(b,c,d,e,f,g,k){a(function(){b.arc(c,d,e,f,g,k)})};this.curveTo=function(b,c,d,e,f,g,k){a(function(){b.curveTo(c,d,e,f,g,k)})};this.close=function(b){a(function(){b.close()})};this.rect=function(b,c,d,e,f){a(function(){b.rect(c,d,e,f)})};this.clip=
function(b){a(function(){b.clip()})};this.strokeColor=function(b,c,d,e,f,g,k,h){a(function(){b.strokeColor(c,d,e,f,g,k,h)})};this.fillColor=function(b,c,d,e,f){a(function(){b.fillColor(c,d,e,f)})};this.strokeLayer=function(b,c,d,e,f){a(function(){b.strokeLayer(c,d,e,f)})};this.fillLayer=function(b,c){a(function(){b.fillLayer(c)})};this.push=function(b){a(function(){b.push()})};this.pop=function(b){a(function(){b.pop()})};this.reset=function(b){a(function(){b.reset()})};this.setTransform=function(b,
c,d,e,f,g,k){a(function(){b.setTransform(c,d,e,f,g,k)})};this.transform=function(b,c,d,e,f,g,k){a(function(){b.transform(c,d,e,f,g,k)})};this.setChannelMask=function(b,c){a(function(){b.setChannelMask(c)})};this.setMiterLimit=function(b,c){a(function(){b.setMiterLimit(c)})};this.dispose=function(b){a(function(){b.dispose()})};this.distort=function(b,c,d,e,f,g,k){a(function(){b.distort(c,d,e,f,g,k)})};this.move=function(b,c,d,e,f){a(function(){b.move(c,d,e,f)})};this.shade=function(b,c){a(function(){b.shade(c)})};
this.scale=function(a){h.style.transform=h.style.WebkitTransform=h.style.MozTransform=h.style.OTransform=h.style.msTransform="scale("+a+","+a+")";f=a;m.style.width=c*f+"px";m.style.height=e*f+"px"};this.getScale=function(){return f};this.flatten=function(){function a(a){var b=[],c;for(c in a.children)b.push(a.children[c]);b.sort(function(a,b){var c=a.z-b.z;if(0!==c)return c;a=a.getElement();b=b.getElement().compareDocumentPosition(a);return b&Node.DOCUMENT_POSITION_PRECEDING?-1:b&Node.DOCUMENT_POSITION_FOLLOWING?
1:0});return b}function b(c,e,f){if(0<c.width&&0<c.height){var g=d.globalAlpha;d.globalAlpha*=c.alpha/255;d.drawImage(c.getCanvas(),e,f);c=a(c);for(var k=0;k<c.length;k++){var h=c[k];b(h,e+h.x,f+h.y)}d.globalAlpha=g}}var c=document.createElement("canvas");c.width=l.width;c.height=l.height;var d=c.getContext("2d");b(l,0,0);return c}};
Guacamole.Display.VisibleLayer=function(b,a){Guacamole.Layer.apply(this,[b,a]);var d=this;this.__unique_id=Guacamole.Display.VisibleLayer.__next_id++;this.alpha=255;this.z=this.y=this.x=0;this.matrix=[1,0,0,1,0,0];this.parent=null;this.children={};var c=d.getCanvas();c.style.position="absolute";c.style.left="0px";c.style.top="0px";var e=document.createElement("div");e.appendChild(c);e.style.width=b+"px";e.style.height=a+"px";e.style.position="absolute";e.style.left="0px";e.style.top="0px";e.style.overflow=
"hidden";var f=this.resize;this.resize=function(a,b){e.style.width=a+"px";e.style.height=b+"px";f(a,b)};this.getElement=function(){return e};var h="translate(0px, 0px)",l="matrix(1, 0, 0, 1, 0, 0)";this.translate=function(a,b){d.x=a;d.y=b;h="translate("+a+"px,"+b+"px)";e.style.transform=e.style.WebkitTransform=e.style.MozTransform=e.style.OTransform=e.style.msTransform=h+" "+l};this.move=function(a,b,c,f){d.parent!==a&&(d.parent&&delete d.parent.children[d.__unique_id],d.parent=a,a.children[d.__unique_id]=
d,a.getElement().appendChild(e));d.translate(b,c);d.z=f;e.style.zIndex=f};this.shade=function(a){d.alpha=a;e.style.opacity=a/255};this.dispose=function(){d.parent&&(delete d.parent.children[d.__unique_id],d.parent=null);e.parentNode&&e.parentNode.removeChild(e)};this.distort=function(a,b,c,f,r,q){d.matrix=[a,b,c,f,r,q];l="matrix("+a+","+b+","+c+","+f+","+r+","+q+")";e.style.transform=e.style.WebkitTransform=e.style.MozTransform=e.style.OTransform=e.style.msTransform=h+" "+l}};
Guacamole.Display.VisibleLayer.__next_id=0;Guacamole.Display.Statistics=function(b){b=b||{};this.processingLag=b.processingLag;this.desktopFps=b.desktopFps;this.serverFps=b.serverFps;this.clientFps=b.clientFps;this.dropRate=b.dropRate};Guacamole=Guacamole||{};Guacamole.Event=function(b){this.type=b;this.timestamp=(new Date).getTime();this.getAge=function(){return(new Date).getTime()-this.timestamp};this.invokeLegacyHandler=function(a){}};
Guacamole.Event.DOMEvent=function(b,a){Guacamole.Event.call(this,b);a=a||[];Array.isArray(a)||(a=[a]);this.preventDefault=function(){a.forEach(function(a){a.preventDefault&&a.preventDefault();a.returnValue=!1})};this.stopPropagation=function(){a.forEach(function(a){a.stopPropagation()})}};Guacamole.Event.DOMEvent.cancelEvent=function(b){b.stopPropagation();b.preventDefault&&b.preventDefault();b.returnValue=!1};
Guacamole.Event.Target=function(){var b={};this.on=function(a,d){var c=b[a];c||(b[a]=c=[]);c.push(d)};this.onEach=function(a,b){a.forEach(function(a){this.on(a,b)},this)};this.dispatch=function(a){a.invokeLegacyHandler(this);var d=b[a.type];if(d)for(var c=0;c<d.length;c++)d[c](a,this)};this.off=function(a,d){a=b[a];if(!a)return!1;for(var c=0;c<a.length;c++)if(a[c]===d)return a.splice(c,1),!0;return!1};this.offEach=function(a,b){var c=!1;a.forEach(function(a){c|=this.off(a,b)},this);return c}};
Guacamole=Guacamole||{};
Guacamole.InputSink=function(){var b=this,a=document.createElement("textarea");a.style.position="fixed";a.style.outline="none";a.style.border="none";a.style.margin="0";a.style.padding="0";a.style.height="0";a.style.width="0";a.style.left="0";a.style.bottom="0";a.style.resize="none";a.style.background="transparent";a.style.color="transparent";a.addEventListener("keypress",function(b){a.value=""},!1);a.addEventListener("compositionend",function(b){b.data&&(a.value="")},!1);a.addEventListener("input",function(b){b.data&&
!b.isComposing&&(a.value="")},!1);a.addEventListener("focus",function(){window.setTimeout(function(){a.click();a.select()},0)},!0);this.focus=function(){window.setTimeout(function(){a.focus()},0)};this.getElement=function(){return a};document.addEventListener("keydown",function(a){if((a=document.activeElement)&&a!==document.body&&(a=a.getBoundingClientRect(),0<a.left+a.width&&0<a.top+a.height))return;b.focus()},!0)};Guacamole=Guacamole||{};
Guacamole.InputStream=function(b,a){var d=this;this.index=a;this.onend=this.onblob=null;this.sendAck=function(a,e){b.sendAck(d.index,a,e)};this.toReadableStream=function(){return new ReadableStream({type:"bytes",start:function(a){var b=new Guacamole.ArrayBufferReader(d);b.ondata=function(b){if(a.byobRequest){var c=a.byobRequest.view,d=Math.min(c.byteLength,b.byteLength),e=new Uint8Array(b,0,d);c.buffer.set(e);a.byobRequest.respond(d);d<b.byteLength&&a.enqueue(b.slice(d))}else a.enqueue(new Uint8Array(b))};
b.onend=function(){a.close()}}})}};Guacamole=Guacamole||{};Guacamole.IntegerPool=function(){var b=this,a=[];this.next_int=0;this.next=function(){return 0<a.length?a.shift():b.next_int++};this.free=function(b){a.push(b)}};Guacamole=Guacamole||{};
Guacamole.JSONReader=function(b){var a=this;b=new Guacamole.StringReader(b);var d="";this.getLength=function(){return d.length};this.getJSON=function(){return JSON.parse(d)};b.ontext=function(b){d+=b;if(a.onprogress)a.onprogress(b.length)};b.onend=function(){if(a.onend)a.onend()};this.onend=this.onprogress=null};Guacamole=Guacamole||{};
Guacamole.Keyboard=function(b){function a(a,b,c){if(!a)return null;var e=a.indexOf("U+");if(0<=e)a=a.substring(e+2),a=String.fromCharCode(parseInt(a,16));else if(1!==a.length||3===b)return B(x[a],b);!0===c?a=a.toUpperCase():!1===c&&(a=a.toLowerCase());c=a.charCodeAt(0);return d(c)}function d(a){return 31>=a||127<=a&&159>=a?65280|a:0<=a&&255>=a?a:256<=a&&1114111>=a?16777216|a:null}function c(){var a=F();if(!a)return!1;do{var b=a;a=F()}while(null!==a);a:{for(var c in e.pressed)if(!y[c]){a=!1;break a}a=
!0}a&&e.reset();return b.defaultPrevented}var e=this,f="_GUAC_KEYBOARD_HANDLED_BY_"+Guacamole.Keyboard._nextID++;this.onkeyup=this.onkeydown=null;var h=!1,l=!1,n=!1;navigator&&navigator.platform&&(navigator.platform.match(/ipad|iphone|ipod/i)?h=!0:navigator.platform.match(/^mac/i)&&(n=l=!0));var m=function(a){var b=this;this.keyCode=a?a.which||a.keyCode:0;this.keyIdentifier=a&&a.keyIdentifier;this.key=a&&a.key;var c=a?"location"in a?a.location:"keyLocation"in a?a.keyLocation:0:0;this.location=c;this.modifiers=
a?Guacamole.Keyboard.ModifierState.fromKeyboardEvent(a):new Guacamole.Keyboard.ModifierState;this.timestamp=(new Date).getTime();this.defaultPrevented=!1;this.keysym=null;this.reliable=!1;this.getAge=function(){return(new Date).getTime()-b.timestamp}},g=function(b){m.call(this,b);this.keysym=a(this.key,this.location)||B(v[this.keyCode],this.location);this.keyupReliable=!h;if(b=this.keysym)b=this.keysym,b=!(0<=b&&255>=b||16777216===(b&4294901760));b&&(this.reliable=!0);if(b=!this.keysym){b=this.keyCode;
var c=this.keyIdentifier;if(c){var d=c.indexOf("U+");-1===d?b=!0:(c=parseInt(c.substring(d+2),16),b=b!==c||65<=b&&90>=b||48<=b&&57>=b?!0:!1)}else b=!1}b&&(this.keysym=a(this.keyIdentifier,this.location,this.modifiers.shift));this.modifiers.meta&&65511!==this.keysym&&65512!==this.keysym?this.keyupReliable=!1:65509===this.keysym&&n&&(this.keyupReliable=!1);b=!this.modifiers.ctrl&&!l;!l||65513!==this.keysym&&65514!==this.keysym||(this.keysym=65027);if(!this.modifiers.alt&&this.modifiers.ctrl||b&&this.modifiers.alt||
this.modifiers.meta||this.modifiers.hyper)this.reliable=!0;C[this.keyCode]=this.keysym};g.prototype=new m;var k=function(a){m.call(this,a);this.keysym=d(this.keyCode);this.reliable=!0};k.prototype=new m;var r=function(b){m.call(this,b);this.keysym=B(v[this.keyCode],this.location)||a(this.key,this.location);e.pressed[this.keysym]||(this.keysym=C[this.keyCode]||this.keysym);this.reliable=!0};r.prototype=new m;var q=[],v={8:[65288],9:[65289],12:[65291,65291,65291,65461],13:[65293],16:[65505,65505,65506],
17:[65507,65507,65508],18:[65513,65513,65514],19:[65299],20:[65509],27:[65307],32:[32],33:[65365,65365,65365,65465],34:[65366,65366,65366,65459],35:[65367,65367,65367,65457],36:[65360,65360,65360,65463],37:[65361,65361,65361,65460],38:[65362,65362,65362,65464],39:[65363,65363,65363,65462],40:[65364,65364,65364,65458],45:[65379,65379,65379,65456],46:[65535,65535,65535,65454],91:[65511],92:[65512],93:[65383],96:[65456],97:[65457],98:[65458],99:[65459],100:[65460],101:[65461],102:[65462],103:[65463],
104:[65464],105:[65465],106:[65450],107:[65451],109:[65453],110:[65454],111:[65455],112:[65470],113:[65471],114:[65472],115:[65473],116:[65474],117:[65475],118:[65476],119:[65477],120:[65478],121:[65479],122:[65480],123:[65481],144:[65407],145:[65300],225:[65027]},x={Again:[65382],AllCandidates:[65341],Alphanumeric:[65328],Alt:[65513,65513,65514],Attn:[64782],AltGraph:[65027],ArrowDown:[65364],ArrowLeft:[65361],ArrowRight:[65363],ArrowUp:[65362],Backspace:[65288],CapsLock:[65509],Cancel:[65385],Clear:[65291],
Convert:[65315],Copy:[64789],Crsel:[64796],CrSel:[64796],CodeInput:[65335],Compose:[65312],Control:[65507,65507,65508],ContextMenu:[65383],Delete:[65535],Down:[65364],End:[65367],Enter:[65293],EraseEof:[64774],Escape:[65307],Execute:[65378],Exsel:[64797],ExSel:[64797],F1:[65470],F2:[65471],F3:[65472],F4:[65473],F5:[65474],F6:[65475],F7:[65476],F8:[65477],F9:[65478],F10:[65479],F11:[65480],F12:[65481],F13:[65482],F14:[65483],F15:[65484],F16:[65485],F17:[65486],F18:[65487],F19:[65488],F20:[65489],F21:[65490],
F22:[65491],F23:[65492],F24:[65493],Find:[65384],GroupFirst:[65036],GroupLast:[65038],GroupNext:[65032],GroupPrevious:[65034],FullWidth:null,HalfWidth:null,HangulMode:[65329],Hankaku:[65321],HanjaMode:[65332],Help:[65386],Hiragana:[65317],HiraganaKatakana:[65319],Home:[65360],Hyper:[65517,65517,65518],Insert:[65379],JapaneseHiragana:[65317],JapaneseKatakana:[65318],JapaneseRomaji:[65316],JunjaMode:[65336],KanaMode:[65325],KanjiMode:[65313],Katakana:[65318],Left:[65361],Meta:[65511,65511,65512],ModeChange:[65406],
NonConvert:[65314],NumLock:[65407],PageDown:[65366],PageUp:[65365],Pause:[65299],Play:[64790],PreviousCandidate:[65342],PrintScreen:[65377],Redo:[65382],Right:[65363],Romaji:[65316],RomanCharacters:null,Scroll:[65300],Select:[65376],Separator:[65452],Shift:[65505,65505,65506],SingleCandidate:[65340],Super:[65515,65515,65516],Tab:[65289],UIKeyInputDownArrow:[65364],UIKeyInputEscape:[65307],UIKeyInputLeftArrow:[65361],UIKeyInputRightArrow:[65363],UIKeyInputUpArrow:[65362],Up:[65362],Undo:[65381],Win:[65511,
65511,65512],Zenkaku:[65320],ZenkakuHankaku:[65322]},t={65027:!0,65505:!0,65506:!0,65507:!0,65508:!0,65509:!0,65511:!0,65512:!0,65513:!0,65514:!0,65515:!0,65516:!0};this.modifiers=new Guacamole.Keyboard.ModifierState;this.pressed={};var y={},u={},C={},D=null,A=null,B=function(a,b){return a?a[b]||a[0]:null};this.press=function(a){if(null!==a){if(!e.pressed[a]&&(e.pressed[a]=!0,e.onkeydown)){var b=e.onkeydown(a);u[a]=b;window.clearTimeout(D);window.clearInterval(A);t[a]||(D=window.setTimeout(function(){A=
window.setInterval(function(){e.onkeyup(a);e.onkeydown(a)},50)},500));return b}return u[a]||!1}};this.release=function(a){if(e.pressed[a]&&(delete e.pressed[a],delete y[a],window.clearTimeout(D),window.clearInterval(A),null!==a&&e.onkeyup))e.onkeyup(a)};this.type=function(a){for(var b=0;b<a.length;b++){var c=a.codePointAt?a.codePointAt(b):a.charCodeAt(b);c=d(c);e.press(c);e.release(c)}};this.reset=function(){for(var a in e.pressed)e.release(parseInt(a));q=[]};var p=function(a,b,c){var d=c.modifiers[a];
a=e.modifiers[a];if(-1===b.indexOf(c.keysym))if(a&&!1===d)for(d=0;d<b.length;d++)e.release(b[d]);else if(!a&&d){for(d=0;d<b.length;d++)if(e.pressed[b[d]])return;b=b[0];c.keysym&&(y[b]=!0);e.press(b)}},w=function(a){p("alt",[65513,65514,65027],a);p("shift",[65505,65506],a);p("ctrl",[65507,65508],a);p("meta",[65511,65512],a);p("hyper",[65515,65516],a);e.modifiers=a.modifiers},F=function(){var a=q[0];if(!a)return null;if(a instanceof g){var b=null,c=[];if(65511===a.keysym||65512===a.keysym){if(1===q.length)return null;
if(q[1].keysym!==a.keysym){if(!q[1].modifiers.meta)return q.shift()}else if(q[1]instanceof g)return q.shift()}a.reliable?(b=a.keysym,c=q.splice(0,1)):q[1]instanceof k?(b=q[1].keysym,c=q.splice(0,2)):q[1]&&(b=a.keysym,c=q.splice(0,1));if(0<c.length){w(a);if(b){e.modifiers.ctrl&&e.modifiers.alt&&!(65<=b&&90>=b||97<=b&&122>=b)&&(255>=b||16777216===(b&4278190080))&&(e.release(65507),e.release(65508),e.release(65513),e.release(65514));var d=!e.press(b);C[a.keyCode]=b;a.keyupReliable||e.release(b);for(b=
0;b<c.length;b++)c[b].defaultPrevented=d}return a}}else{if(a instanceof r&&!h){if(b=a.keysym)e.release(b),delete C[a.keyCode],a.defaultPrevented=!0;else return e.reset(),a;w(a)}return q.shift()}return null},z=function(a){return a[f]?!1:a[f]=!0};this.listenTo=function(a){a.addEventListener("keydown",function(a){if(e.onkeydown&&z(a)){var b=new g(a);a.isComposing||229===b.keyCode||(q.push(b),c()&&a.preventDefault())}},!0);a.addEventListener("keypress",function(a){(e.onkeydown||e.onkeyup)&&z(a)&&(q.push(new k(a)),
c()&&a.preventDefault())},!0);a.addEventListener("keyup",function(a){e.onkeyup&&z(a)&&(a.preventDefault(),q.push(new r(a)),c())},!0);var b=function(a){(e.onkeydown||e.onkeyup)&&z(a)&&a.data&&!a.isComposing&&e.type(a.data)};a.addEventListener("input",b,!1);a.addEventListener("compositionend",function(a){(e.onkeydown||e.onkeyup)&&z(a)&&a.data&&e.type(a.data)},!1);a.addEventListener("compositionstart",function(c){a.removeEventListener("input",b,!1)},!1)};b&&e.listenTo(b)};
Guacamole.Keyboard._nextID=0;Guacamole.Keyboard.ModifierState=function(){this.hyper=this.meta=this.alt=this.ctrl=this.shift=!1};Guacamole.Keyboard.ModifierState.fromKeyboardEvent=function(b){var a=new Guacamole.Keyboard.ModifierState;a.shift=b.shiftKey;a.ctrl=b.ctrlKey;a.alt=b.altKey;a.meta=b.metaKey;b.getModifierState&&(a.hyper=b.getModifierState("OS")||b.getModifierState("Super")||b.getModifierState("Hyper")||b.getModifierState("Win"));return a};Guacamole=Guacamole||{};
Guacamole.KeyEventInterpreter=function(b){if(void 0===b||null===b)b=0;var a={};[{keysym:65027,name:"AltGr"},{keysym:65288,name:"Backspace"},{keysym:65289,name:"Tab"},{keysym:65291,name:"Clear"},{keysym:65293,name:"Return",value:"\n"},{keysym:65299,name:"Pause"},{keysym:65300,name:"Scroll"},{keysym:65301,name:"SysReq"},{keysym:65307,name:"Escape"},{keysym:65360,name:"Home"},{keysym:65361,name:"Left"},{keysym:65362,name:"Up"},{keysym:65363,name:"Right"},{keysym:65364,name:"Down"},{keysym:65365,name:"Page Up"},
{keysym:65366,name:"Page Down"},{keysym:65367,name:"End"},{keysym:65379,name:"Insert"},{keysym:65381,name:"Undo"},{keysym:65386,name:"Help"},{keysym:65407,name:"Num"},{keysym:65408,name:"Space",value:" "},{keysym:65421,name:"Enter",value:"\n"},{keysym:65429,name:"Home"},{keysym:65430,name:"Left"},{keysym:65431,name:"Up"},{keysym:65432,name:"Right"},{keysym:65433,name:"Down"},{keysym:65434,name:"Page Up"},{keysym:65435,name:"Page Down"},{keysym:65436,name:"End"},{keysym:65438,name:"Insert"},{keysym:65450,
name:"*",value:"*"},{keysym:65451,name:"+",value:"+"},{keysym:65453,name:"-",value:"-"},{keysym:65454,name:".",value:"."},{keysym:65455,name:"/",value:"/"},{keysym:65456,name:"0",value:"0"},{keysym:65457,name:"1",value:"1"},{keysym:65458,name:"2",value:"2"},{keysym:65459,name:"3",value:"3"},{keysym:65460,name:"4",value:"4"},{keysym:65461,name:"5",value:"5"},{keysym:65462,name:"6",value:"6"},{keysym:65463,name:"7",value:"7"},{keysym:65464,name:"8",value:"8"},{keysym:65465,name:"9",value:"9"},{keysym:65470,
name:"F1"},{keysym:65471,name:"F2"},{keysym:65472,name:"F3"},{keysym:65473,name:"F4"},{keysym:65474,name:"F5"},{keysym:65475,name:"F6"},{keysym:65476,name:"F7"},{keysym:65477,name:"F8"},{keysym:65478,name:"F9"},{keysym:65479,name:"F10"},{keysym:65480,name:"F11"},{keysym:65481,name:"F12"},{keysym:65482,name:"F13"},{keysym:65483,name:"F14"},{keysym:65484,name:"F15"},{keysym:65485,name:"F16"},{keysym:65486,name:"F17"},{keysym:65487,name:"F18"},{keysym:65488,name:"F19"},{keysym:65489,name:"F20"},{keysym:65490,
name:"F21"},{keysym:65491,name:"F22"},{keysym:65492,name:"F23"},{keysym:65493,name:"F24"},{keysym:65505,name:"Shift"},{keysym:65506,name:"Shift"},{keysym:65507,name:"Ctrl"},{keysym:65508,name:"Ctrl"},{keysym:65509,name:"Caps"},{keysym:65511,name:"Meta"},{keysym:65512,name:"Meta"},{keysym:65513,name:"Alt"},{keysym:65514,name:"Alt"},{keysym:65515,name:"Super"},{keysym:65516,name:"Super"},{keysym:65517,name:"Hyper"},{keysym:65518,name:"Hyper"},{keysym:65535,name:"Delete"}].forEach(function(b){a[b.keysym]=
new Guacamole.KeyEventInterpreter.KeyDefinition(b)});var d=[];this.handleKeyEvent=function(c){var e=parseInt(c[0]),f=parseInt(c[1]);c=parseInt(c[2])-b;if(e in a)e=a[e];else{if(0>e||255<e&&16842751!=(e|65535))var h=null;else h=String.fromCharCode(e&65535),h=new Guacamole.KeyEventInterpreter.KeyDefinition({keysym:e,name:h,value:h});e=null!=h?h:new Guacamole.KeyEventInterpreter.KeyDefinition({keysym:e,name:"0x"+String(e.toString(16))})}d.push(new Guacamole.KeyEventInterpreter.KeyEvent({definition:e,
pressed:f,timestamp:c}))};this.getEvents=function(){return d}};Guacamole.KeyEventInterpreter.KeyDefinition=function(b){b=b||{};this.keysym=parseInt(b.keysym);this.name=b.name;this.value=b.value};Guacamole.KeyEventInterpreter.KeyEvent=function(b){b=b||{};this.definition=b.definition;this.pressed=!!b.pressed;this.timestamp=b.timestamp};Guacamole=Guacamole||{};
Guacamole.Layer=function(b,a){function d(a,b,d,e){a=d+a;b=e+b;c.resize(a>c.width?a:c.width,b>c.height?b:c.height)}var c=this,e=document.createElement("canvas"),f=e.getContext("2d");f.save();var h=!0,l=!0,n=0,m={1:"destination-in",2:"destination-out",4:"source-in",6:"source-atop",8:"source-out",9:"destination-atop",10:"xor",11:"destination-over",12:"copy",14:"source-over",15:"lighter"},g=function(a,b){a=a||0;b=b||0;var d=64*Math.ceil(a/64),g=64*Math.ceil(b/64);if(e.width!==d||e.height!==g){var k=null;
h||0===e.width||0===e.height||(k=document.createElement("canvas"),k.width=Math.min(c.width,a),k.height=Math.min(c.height,b),k.getContext("2d").drawImage(e,0,0,k.width,k.height,0,0,k.width,k.height));var l=f.globalCompositeOperation;e.width=d;e.height=g;k&&f.drawImage(k,0,0,k.width,k.height,0,0,k.width,k.height);f.globalCompositeOperation=l;n=0;f.save()}else c.reset();c.width=a;c.height=b};this.autosize=!1;this.width=b;this.height=a;this.getCanvas=function(){return e};this.toCanvas=function(){var a=
document.createElement("canvas");a.width=c.width;a.height=c.height;a.getContext("2d").drawImage(c.getCanvas(),0,0);return a};this.resize=function(a,b){a===c.width&&b===c.height||g(a,b)};this.drawImage=function(a,b,e){c.autosize&&d(a,b,e.width,e.height);f.drawImage(e,a,b);h=!1};this.transfer=function(a,b,e,g,l,n,m,u){var k=a.getCanvas();if(!(b>=k.width||e>=k.height)&&(b+g>k.width&&(g=k.width-b),e+l>k.height&&(l=k.height-e),0!==g&&0!==l)){c.autosize&&d(n,m,g,l);a=a.getCanvas().getContext("2d").getImageData(b,
e,g,l);b=f.getImageData(n,m,g,l);for(e=0;e<g*l*4;e+=4){k=new Guacamole.Layer.Pixel(a.data[e],a.data[e+1],a.data[e+2],a.data[e+3]);var v=new Guacamole.Layer.Pixel(b.data[e],b.data[e+1],b.data[e+2],b.data[e+3]);u(k,v);b.data[e]=v.red;b.data[e+1]=v.green;b.data[e+2]=v.blue;b.data[e+3]=v.alpha}f.putImageData(b,n,m);h=!1}};this.put=function(a,b,e,g,l,n,m){var k=a.getCanvas();b>=k.width||e>=k.height||(b+g>k.width&&(g=k.width-b),e+l>k.height&&(l=k.height-e),0!==g&&0!==l&&(c.autosize&&d(n,m,g,l),a=a.getCanvas().getContext("2d").getImageData(b,
e,g,l),f.putImageData(a,n,m),h=!1))};this.copy=function(a,b,e,g,l,n,m){a=a.getCanvas();b>=a.width||e>=a.height||(b+g>a.width&&(g=a.width-b),e+l>a.height&&(l=a.height-e),0!==g&&0!==l&&(c.autosize&&d(n,m,g,l),f.drawImage(a,b,e,g,l,n,m,g,l),h=!1))};this.moveTo=function(a,b){l&&(f.beginPath(),l=!1);c.autosize&&d(a,b,0,0);f.moveTo(a,b)};this.lineTo=function(a,b){l&&(f.beginPath(),l=!1);c.autosize&&d(a,b,0,0);f.lineTo(a,b)};this.arc=function(a,b,e,g,h,n){l&&(f.beginPath(),l=!1);c.autosize&&d(a,b,0,0);f.arc(a,
b,e,g,h,n)};this.curveTo=function(a,b,e,g,h,n){l&&(f.beginPath(),l=!1);c.autosize&&d(h,n,0,0);f.bezierCurveTo(a,b,e,g,h,n)};this.close=function(){f.closePath();l=!0};this.rect=function(a,b,e,g){l&&(f.beginPath(),l=!1);c.autosize&&d(a,b,e,g);f.rect(a,b,e,g)};this.clip=function(){f.clip();l=!0};this.strokeColor=function(a,b,c,d,e,g,n){f.lineCap=a;f.lineJoin=b;f.lineWidth=c;f.strokeStyle="rgba("+d+","+e+","+g+","+n/255+")";f.stroke();h=!1;l=!0};this.fillColor=function(a,b,c,d){f.fillStyle="rgba("+a+
","+b+","+c+","+d/255+")";f.fill();h=!1;l=!0};this.strokeLayer=function(a,b,c,d){f.lineCap=a;f.lineJoin=b;f.lineWidth=c;f.strokeStyle=f.createPattern(d.getCanvas(),"repeat");f.stroke();h=!1;l=!0};this.fillLayer=function(a){f.fillStyle=f.createPattern(a.getCanvas(),"repeat");f.fill();h=!1;l=!0};this.push=function(){f.save();n++};this.pop=function(){0<n&&(f.restore(),n--)};this.reset=function(){for(;0<n;)f.restore(),n--;f.restore();f.save();f.beginPath();l=!1};this.setTransform=function(a,b,c,d,e,g){f.setTransform(a,
b,c,d,e,g)};this.transform=function(a,b,c,d,e,g){f.transform(a,b,c,d,e,g)};this.setChannelMask=function(a){f.globalCompositeOperation=m[a]};this.setMiterLimit=function(a){f.miterLimit=a};g(b,a);e.style.zIndex=-1};Guacamole.Layer.ROUT=2;Guacamole.Layer.ATOP=6;Guacamole.Layer.XOR=10;Guacamole.Layer.ROVER=11;Guacamole.Layer.OVER=14;Guacamole.Layer.PLUS=15;Guacamole.Layer.RIN=1;Guacamole.Layer.IN=4;Guacamole.Layer.OUT=8;Guacamole.Layer.RATOP=9;Guacamole.Layer.SRC=12;
Guacamole.Layer.Pixel=function(b,a,d,c){this.red=b;this.green=a;this.blue=d;this.alpha=c};Guacamole=Guacamole||{};
Guacamole.Mouse=function(b){function a(){f=c.touchMouseThreshold}function d(a){var b=a.deltaY||-a.wheelDeltaY||-a.wheelDelta;b?1===a.deltaMode?b=a.deltaY*c.PIXELS_PER_LINE:2===a.deltaMode&&(b=a.deltaY*c.PIXELS_PER_PAGE):b=a.detail*c.PIXELS_PER_LINE;h+=b;if(h<=-c.scrollThreshold){do c.click(Guacamole.Mouse.State.Buttons.UP),h+=c.scrollThreshold;while(h<=-c.scrollThreshold);h=0}if(h>=c.scrollThreshold){do c.click(Guacamole.Mouse.State.Buttons.DOWN),h-=c.scrollThreshold;while(h>=c.scrollThreshold);h=
0}Guacamole.Event.DOMEvent.cancelEvent(a)}Guacamole.Mouse.Event.Target.call(this);var c=this;this.touchMouseThreshold=3;this.scrollThreshold=53;this.PIXELS_PER_LINE=18;this.PIXELS_PER_PAGE=16*this.PIXELS_PER_LINE;var e=[Guacamole.Mouse.State.Buttons.LEFT,Guacamole.Mouse.State.Buttons.MIDDLE,Guacamole.Mouse.State.Buttons.RIGHT],f=0,h=0;b.addEventListener("contextmenu",function(a){Guacamole.Event.DOMEvent.cancelEvent(a)},!1);b.addEventListener("mousemove",function(a){f?(Guacamole.Event.DOMEvent.cancelEvent(a),
f--):c.move(Guacamole.Position.fromClientPosition(b,a.clientX,a.clientY),a)},!1);b.addEventListener("mousedown",function(a){if(f)Guacamole.Event.DOMEvent.cancelEvent(a);else{var b=e[a.button];b&&c.press(b,a)}},!1);b.addEventListener("mouseup",function(a){if(f)Guacamole.Event.DOMEvent.cancelEvent(a);else{var b=e[a.button];b&&c.release(b,a)}},!1);b.addEventListener("mouseout",function(a){a||(a=window.event);for(var d=a.relatedTarget||a.toElement;d;){if(d===b)return;d=d.parentNode}c.reset(a);c.out(a)},
!1);b.addEventListener("selectstart",function(a){Guacamole.Event.DOMEvent.cancelEvent(a)},!1);b.addEventListener("touchmove",a,!1);b.addEventListener("touchstart",a,!1);b.addEventListener("touchend",a,!1);window.WheelEvent?b.addEventListener("wheel",d,!1):(b.addEventListener("DOMMouseScroll",d,!1),b.addEventListener("mousewheel",d,!1));var l=function(){var a=document.createElement("div");if(!("cursor"in a.style))return!1;try{a.style.cursor="url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX///+nxBvIAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg\x3d\x3d) 0 0, auto"}catch(m){return!1}return/\burl\([^()]*\)\s+0\s+0\b/.test(a.style.cursor||
"")}();this.setCursor=function(a,c,d){return l?(a=a.toDataURL("image/png"),b.style.cursor="url("+a+") "+c+" "+d+", auto",!0):!1}};Guacamole.Mouse.State=function(b){var a=function(a,b,e,f,h,l,n){return{x:a,y:b,left:e,middle:f,right:h,up:l,down:n}};b=1<arguments.length?a.apply(this,arguments):b||{};Guacamole.Position.call(this,b);this.left=b.left||!1;this.middle=b.middle||!1;this.right=b.right||!1;this.up=b.up||!1;this.down=b.down||!1};
Guacamole.Mouse.State.Buttons={LEFT:"left",MIDDLE:"middle",RIGHT:"right",UP:"up",DOWN:"down"};Guacamole.Mouse.Event=function(b,a,d){Guacamole.Event.DOMEvent.call(this,b,d);var c="on"+this.type;this.state=a;this.invokeLegacyHandler=function(a){a[c]&&(this.preventDefault(),this.stopPropagation(),a[c](this.state))}};
Guacamole.Mouse.Event.Target=function(){Guacamole.Event.Target.call(this);this.currentState=new Guacamole.Mouse.State;this.press=function(b,a){this.currentState[b]||(this.currentState[b]=!0,this.dispatch(new Guacamole.Mouse.Event("mousedown",this.currentState,a)))};this.release=function(b,a){this.currentState[b]&&(this.currentState[b]=!1,this.dispatch(new Guacamole.Mouse.Event("mouseup",this.currentState,a)))};this.click=function(b,a){this.press(b,a);this.release(b,a)};this.move=function(b,a){if(this.currentState.x!==
b.x||this.currentState.y!==b.y)this.currentState.x=b.x,this.currentState.y=b.y,this.dispatch(new Guacamole.Mouse.Event("mousemove",this.currentState,a))};this.out=function(b){this.dispatch(new Guacamole.Mouse.Event("mouseout",this.currentState,b))};this.reset=function(b){for(var a in Guacamole.Mouse.State.Buttons)this.release(Guacamole.Mouse.State.Buttons[a],b)}};
Guacamole.Mouse.Touchpad=function(b){Guacamole.Mouse.Event.Target.call(this);var a=this;this.scrollThreshold=20*(window.devicePixelRatio||1);this.clickTimingThreshold=250;this.clickMoveThreshold=10*(window.devicePixelRatio||1);this.currentState=new Guacamole.Mouse.State;var d=0,c=0,e=0,f=0,h=0,l={1:"left",2:"right",3:"middle"},n=!1,m=null;b.addEventListener("touchend",function(b){b.preventDefault();if(n&&0===b.touches.length){var c=(new Date).getTime(),e=l[d];a.currentState[e]&&(a.release(e,b),m&&
(window.clearTimeout(m),m=null));c-f<=a.clickTimingThreshold&&h<a.clickMoveThreshold&&(a.press(e,b),m=window.setTimeout(function(){a.release(e,b);n=!1},a.clickTimingThreshold));m||(n=!1)}},!1);b.addEventListener("touchstart",function(a){a.preventDefault();d=Math.min(a.touches.length,3);m&&(window.clearTimeout(m),m=null);n||(n=!0,a=a.touches[0],c=a.clientX,e=a.clientY,f=(new Date).getTime(),h=0)},!1);b.addEventListener("touchmove",function(g){g.preventDefault();var k=g.touches[0],l=k.clientX-c,m=k.clientY-
e;h+=Math.abs(l)+Math.abs(m);if(1===d){var v=1+h/((new Date).getTime()-f),n=new Guacamole.Position(a.currentState);n.x+=l*v;n.y+=m*v;n.x=Math.min(Math.max(0,n.x),b.offsetWidth-1);n.y=Math.min(Math.max(0,n.y),b.offsetHeight-1);a.move(n,g);c=k.clientX;e=k.clientY}else 2===d&&Math.abs(m)>=a.scrollThreshold&&(a.click(0<m?"down":"up",g),c=k.clientX,e=k.clientY)},!1)};
Guacamole.Mouse.Touchscreen=function(b){function a(a){var b=a.touches[0]||a.changedTouches[0];a=b.clientX-h;b=b.clientY-l;return Math.sqrt(a*a+b*b)>=e.clickMoveThreshold}function d(a){a=a.touches[0];f=!0;h=a.clientX;l=a.clientY}function c(){window.clearTimeout(n);window.clearTimeout(m);f=!1}Guacamole.Mouse.Event.Target.call(this);var e=this,f=!1,h=null,l=null,n=null,m=null;this.scrollThreshold=20*(window.devicePixelRatio||1);this.clickTimingThreshold=250;this.clickMoveThreshold=16*(window.devicePixelRatio||
1);this.longPressThreshold=500;b.addEventListener("touchend",function(d){if(f)if(0!==d.touches.length||1!==d.changedTouches.length)c();else if(window.clearTimeout(m),e.release(Guacamole.Mouse.State.Buttons.LEFT,d),!a(d)&&(d.preventDefault(),!e.currentState.left)){var g=d.changedTouches[0];e.move(Guacamole.Position.fromClientPosition(b,g.clientX,g.clientY));e.press(Guacamole.Mouse.State.Buttons.LEFT,d);n=window.setTimeout(function(){e.release(Guacamole.Mouse.State.Buttons.LEFT,d);c()},e.clickTimingThreshold)}},
!1);b.addEventListener("touchstart",function(a){1!==a.touches.length?c():(a.preventDefault(),d(a),window.clearTimeout(n),m=window.setTimeout(function(){var d=a.touches[0];e.move(Guacamole.Position.fromClientPosition(b,d.clientX,d.clientY));e.click(Guacamole.Mouse.State.Buttons.RIGHT,a);c()},e.longPressThreshold))},!1);b.addEventListener("touchmove",function(d){if(f)if(a(d)&&window.clearTimeout(m),1!==d.touches.length)c();else if(e.currentState.left){d.preventDefault();var g=d.touches[0];e.move(Guacamole.Position.fromClientPosition(b,
g.clientX,g.clientY),d)}},!1)};Guacamole=Guacamole=Guacamole||{};Guacamole.Object=function(b,a){var d=this,c={};this.index=a;this.onbody=function(a,b,d){var e=c[d];if(e){var f=e.shift();0===e.length&&delete c[d];d=f}else d=null;d&&d(a,b)};this.onundefine=null;this.requestInputStream=function(a,f){if(f){var e=c[a];e||(e=[],c[a]=e);e.push(f)}b.requestObjectInputStream(d.index,a)};this.createOutputStream=function(a,c){return b.createObjectOutputStream(d.index,a,c)}};Guacamole.Object.ROOT_STREAM="/";
Guacamole.Object.STREAM_INDEX_MIMETYPE="application/vnd.glyptodon.guacamole.stream-index+json";Guacamole=Guacamole||{};
Guacamole.OnScreenKeyboard=function(b){var a=this,d={},c={},e=[],f=function(a,b){a.classList?a.classList.add(b):a.className+=" "+b},h=function(a,b){a.classList?a.classList.remove(b):a.className=a.className.replace(/([^ ]+)[ ]*/g,function(a,c){return c===b?"":a})},l=0,n=function(a,b,c,d){this.width=b;this.height=c;this.scale=function(e){a.style.width=b*e+"px";a.style.height=c*e+"px";d&&(a.style.lineHeight=c*e+"px",a.style.fontSize=e+"px")}},m=function(b){b=a.keys[b];if(!b)return null;for(var c=b.length-
1;0<=c;c--){var e=b[c];a:{var f=e.requires;for(var g=0;g<f.length;g++)if(!(f[g]in d)){f=!1;break a}f=!0}if(f)return e}return null},g=function(b,e){if(!c[b]){f(e,"guac-keyboard-pressed");e=m(b);if(e.modifier){var g="guac-keyboard-modifier-"+q(e.modifier),l=d[e.modifier];if(void 0===l){if(f(r,g),(d[e.modifier]=e.keysym)&&a.onkeydown)a.onkeydown(e.keysym)}else if(h(r,g),delete d[e.modifier],l&&a.onkeyup)a.onkeyup(l)}else if(a.onkeydown)a.onkeydown(e.keysym);c[b]=!0}},k=function(b,d){if(c[b]){h(d,"guac-keyboard-pressed");
d=m(b);if(!d.modifier&&a.onkeyup)a.onkeyup(d.keysym);c[b]=!1}},r=document.createElement("div");r.className="guac-keyboard";r.onselectstart=r.onmousemove=r.onmouseup=r.onmousedown=function(a){l&&l--;a.stopPropagation();return!1};this.touchMouseThreshold=3;this.onkeyup=this.onkeydown=null;this.layout=new Guacamole.OnScreenKeyboard.Layout(b);this.getElement=function(){return r};this.resize=function(b){b=Math.floor(10*b/a.layout.width)/10;for(var c=0;c<e.length;c++)e[c].scale(b)};this.keys=function(a){var c=
{},d;for(d in b.keys){var e=d;var f=d;var g=a[d];if(g instanceof Array){for(var h=[],l=0;l<g.length;l++)h.push(new Guacamole.OnScreenKeyboard.Key(g[l],f));f=h}else f="number"===typeof g?[new Guacamole.OnScreenKeyboard.Key({name:f,keysym:g})]:"string"===typeof g?[new Guacamole.OnScreenKeyboard.Key({name:f,title:g})]:[new Guacamole.OnScreenKeyboard.Key(g,f)];c[e]=f}return c}(b.keys);var q=function(a){return a.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()};(function u(b,
c,d){var h,m=document.createElement("div");d&&f(m,"guac-keyboard-"+q(d));if(c instanceof Array)for(f(m,"guac-keyboard-group"),h=0;h<c.length;h++)u(m,c[h]);else if(c instanceof Object){f(m,"guac-keyboard-group");var r=Object.keys(c).sort();for(h=0;h<r.length;h++)d=r[h],u(m,c[d],d)}else if("number"===typeof c)f(m,"guac-keyboard-gap"),e.push(new n(m,c,c));else if("string"===typeof c){h=c;1===h.length&&(h="0x"+h.charCodeAt(0).toString(16));f(m,"guac-keyboard-key-container");var t=document.createElement("div");
t.className="guac-keyboard-key guac-keyboard-key-"+q(h);if(d=a.keys[c])for(h=0;h<d.length;h++){r=d[h];var p=document.createElement("div");p.className="guac-keyboard-cap";p.textContent=r.title;for(var w=0;w<r.requires.length;w++){var x=r.requires[w];f(p,"guac-keyboard-requires-"+q(x));f(t,"guac-keyboard-uses-"+q(x))}t.appendChild(p)}m.appendChild(t);e.push(new n(m,a.layout.keyWidths[c]||1,1,!0));h=function(a){a.preventDefault();0===l&&k(c,t)};t.addEventListener("touchstart",function(b){b.preventDefault();
l=a.touchMouseThreshold;g(c,t)},!0);t.addEventListener("touchend",function(b){b.preventDefault();l=a.touchMouseThreshold;k(c,t)},!0);t.addEventListener("mousedown",function(a){a.preventDefault();0===l&&g(c,t)},!0);t.addEventListener("mouseup",h,!0);t.addEventListener("mouseout",h,!0)}b.appendChild(m)})(r,b.layout)};Guacamole.OnScreenKeyboard.Layout=function(b){this.language=b.language;this.type=b.type;this.keys=b.keys;this.layout=b.layout;this.width=b.width;this.keyWidths=b.keyWidths||{}};
Guacamole.OnScreenKeyboard.Key=function(b,a){this.name=a||b.name;this.title=b.title||this.name;(a=b.keysym)||((a=this.title)&&1===a.length?(a=a.charCodeAt(0),a=0<=a&&255>=a?a:256<=a&&1114111>=a?16777216|a:null):a=null);this.keysym=a;this.modifier=b.modifier;this.requires=b.requires||[]};Guacamole=Guacamole||{};Guacamole.OutputStream=function(b,a){var d=this;this.index=a;this.onack=null;this.sendBlob=function(a){b.sendBlob(d.index,a)};this.sendEnd=function(){b.endStream(d.index)}};
Guacamole=Guacamole||{};
Guacamole.Parser=function(){var b=this,a="",d=[],c=-1,e=0,f=0;this.receive=function(h,l){l?a=h:(4096<e&&c>=e&&(a=a.substring(e),c-=e,e=0),a=a.length?a+h:h);for(;c<a.length;){if(c>=e){h=Guacamole.Parser.codePointCount(a,e,c);if(h<f){c+=f-h;continue}else if(f&&65536<=a.codePointAt(c-1)){c++;continue}h=a.substring(e,c);var n=a.substring(c,c+1);d.push(h);if(";"===n){h=d.shift();if(null!==b.oninstruction)b.oninstruction(h,d);d=[];l||c+1!==a.length||(c=-1,a="")}else if(","!==n)throw Error('Element terminator of instruction was not ";" nor ",".');e=
c+1}h=a.indexOf(".",e);if(-1!==h){f=parseInt(a.substring(c+1,h));if(isNaN(f))throw Error("Non-numeric character in element length.");e=h+1;c=e+f}else{e=a.length;break}}};this.oninstruction=null};Guacamole.Parser.codePointCount=function(b,a,d){b=b.substring(a||0,d);a=b.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);return b.length-(a?a.length:0)};
Guacamole.Parser.toInstruction=function(b){for(var a=function(a){a=""+a;return Guacamole.Parser.codePointCount(a)+"."+a},d=a(b[0]),c=1;c<b.length;c++)d+=","+a(b[c]);return d+";"};Guacamole=Guacamole||{};
Guacamole.Position=function(b){b=b||{};this.x=b.x||0;this.y=b.y||0;this.fromClientPosition=function(a,b,c){this.x=b-a.offsetLeft;this.y=c-a.offsetTop;for(a=a.offsetParent;a&&a!==document.body;)this.x-=a.offsetLeft-a.scrollLeft,this.y-=a.offsetTop-a.scrollTop,a=a.offsetParent;a&&(b=document.body.scrollTop||document.documentElement.scrollTop,this.x-=a.offsetLeft-(document.body.scrollLeft||document.documentElement.scrollLeft),this.y-=a.offsetTop-b)}};
Guacamole.Position.fromClientPosition=function(b,a,d){var c=new Guacamole.Position;c.fromClientPosition(b,a,d);return c};Guacamole=Guacamole||{};Guacamole.RawAudioFormat=function(b){this.bytesPerSample=b.bytesPerSample;this.channels=b.channels;this.rate=b.rate};
Guacamole.RawAudioFormat.parse=function(b){var a=null,d=1;if("audio/L8;"===b.substring(0,9)){b=b.substring(9);var c=1}else if("audio/L16;"===b.substring(0,10))b=b.substring(10),c=2;else return null;b=b.split(",");for(var e=0;e<b.length;e++){var f=b[e],h=f.indexOf("\x3d");if(-1===h)return null;var l=f.substring(0,h);f=f.substring(h+1);switch(l){case "channels":d=parseInt(f);break;case "rate":a=parseInt(f);break;default:return null}}return null===a?null:new Guacamole.RawAudioFormat({bytesPerSample:c,
channels:d,rate:a})};Guacamole=Guacamole||{};
Guacamole.SessionRecording=function(b,a){void 0===a&&(a=1E3);var d=this,c=null,e=[],f=0,h=new Guacamole.SessionRecording._PlaybackTunnel,l=new Guacamole.Client(h),n=-1,m=null,g=null,k=0,r=null,q=0,v=0,x=!1,t=null,y=null,u=null,C=function(a,b,c){if(!x||a!==w){var e=new Guacamole.Parser;e.oninstruction=b;var f=0,g=new FileReader;b=function(){if(!x||a!==w){if(2===g.readyState)try{e.receive(g.result)}catch(O){if(d.onerror)d.onerror(O.message);return}if(f>=a.size)c&&c();else{var b=a.slice(f,f+262144);
f+=b.size;g.readAsText(b)}}};g.onload=b;b()}},D=function(a){a=a.length;for(var b=a+3;10<=a;)b++,a=Math.floor(a/10);return b};l.connect();l.getDisplay().showCursor(!1);var A=null,B=function(a,b){v+=D(a);for(var c=0;c<b.length;c++)v+=D(b[c]);if("sync"===a){a=parseInt(b[0]);b=new Guacamole.SessionRecording._Frame(a,q,v);e.push(b);q=v;1===e.length&&(A=new Guacamole.KeyEventInterpreter(a));if(1===e.length||16384<=v-e[f].start&&5E3<=a-e[f].timestamp)b.keyframe=!0,f=e.length-1;if(d.onprogress)d.onprogress(d.getDuration(),
v)}else"key"===a&&A.handleKeyEvent(b)},p=function(){if(d.onload)d.onload()};if(b instanceof Blob){var w=b;C(w,B,p)}else{c=b;w=new Blob;var F=!1,z="";c.oninstruction=function(a,b){z+=a.length+"."+a;b.forEach(function(a){z+=","+a.length+"."+a});z+=";";262144<=z.length&&(w=new Blob([w,z]),z="");B(a,b)};c.onerror=function(a){F=!0;if(d.onerror)d.onerror(a.message)};c.onstatechange=function(a){if(a===Guacamole.Tunnel.State.CLOSED){z.length&&(w=new Blob([w,z]),z="");if(d.onkeyevents)d.onkeyevents(A.getEvents());
F||p()}}}var E=function(a){return 0===e.length?0:a-e[0].timestamp},L=function K(a,b,c){if(a===b){if(0===a)return a;if(E(e[a].timestamp)>c)return a-1}var d=Math.floor((a+b)/2),f=E(e[d].timestamp);return c<f&&d>a?K(a,d-1,c):c>f&&d<b?K(d+1,b,c):d},M=function(a,b){var c=e[a];C(w.slice(c.start,c.end),function(a,b){h.receiveInstruction(a,b)},function(){c.keyframe&&!c.clientState&&l.exportState(function(a){c.clientState=new Blob([JSON.stringify(a)])});n=a;b&&b()})},I=function(a,b,c){H();for(var f=r={aborted:!1},
g=a,h=function P(){d.onseek&&n>g&&(k=E(e[n].timestamp),d.onseek(k,n-g,a-g));f.aborted||(n<a?M(n+1,P):b())},m=function(){var a=c?Math.max(c-(new Date).getTime(),0):0;a?(y&&clearTimeout(y),y=window.setTimeout(function(){y=null;h()},a)):h()};0<=g;g--){var p=e[g];if(g===n)break;if(p.clientState){p.clientState.text().then(function(a){l.importState(JSON.parse(a));n=g;m()});return}}m()},H=function(){r&&(r.aborted=!0,r=null)},G=function J(){if(d.isPlaying())if(n+1<e.length){var b=e[n+1],c=Date.now()-g;b=
E(b.timestamp)-m-c;var f=0<=a?a*Math.floor((k+a)/a)-k:b;b<=f?I(n+1,function(){u=Date.now();J()},Date.now()+b):(y&&window.clearTimeout(y),y=window.setTimeout(function(){y=null;k+=f;if(d.onseek)d.onseek(k);u=Date.now();J()},f))}else d.pause()};this.onseek=this.onkeyevents=this.onpause=this.onplay=this.onprogress=this.onabort=this.onerror=this.onload=null;this.connect=function(a){c&&c.connect(a)};this.disconnect=function(){c&&c.disconnect()};this.abort=function(){if(!x){x=!0;if(d.onabort)d.onabort();
c&&c.disconnect()}};this.getDisplay=function(){return l.getDisplay()};this.isPlaying=function(){return!!g};this.getPosition=function(){return k};this.getDuration=function(){return 0===e.length?0:E(e[e.length-1].timestamp)};this.play=function(){if(!d.isPlaying()&&n+1<e.length){if(d.onplay)d.onplay();m=k;g=Date.now();u=Date.now();G()}};this.seek=function(a,b){if(0!==e.length){d.cancel();var c=d.isPlaying();d.pause();t=function(){t=null;c&&(d.play(),c=null);b&&b()};var f=L(0,e.length-1,a);I(f,function(){k=
a;if(d.onseek)d.onseek(a);t()})}};this.cancel=function(){t&&(H(),t())};this.pause=function(){H();y&&clearTimeout(y);k+=Date.now()-u;if(d.isPlaying()){if(d.onpause)d.onpause();g=m=u=null}}};Guacamole.SessionRecording._Frame=function(b,a,d){this.keyframe=!1;this.timestamp=b;this.start=a;this.end=d;this.clientState=null};
Guacamole.SessionRecording._PlaybackTunnel=function(){var b=this;this.connect=function(a){};this.sendMessage=function(a){};this.disconnect=function(){};this.receiveInstruction=function(a,d){if(b.oninstruction)b.oninstruction(a,d)}};Guacamole=Guacamole||{};Guacamole.Status=function(b,a){var d=this;this.code=b;this.message=a;this.isError=function(){return 0>d.code||255<d.code}};
Guacamole.Status.Code={SUCCESS:0,UNSUPPORTED:256,SERVER_ERROR:512,SERVER_BUSY:513,UPSTREAM_TIMEOUT:514,UPSTREAM_ERROR:515,RESOURCE_NOT_FOUND:516,RESOURCE_CONFLICT:517,RESOURCE_CLOSED:518,UPSTREAM_NOT_FOUND:519,UPSTREAM_UNAVAILABLE:520,SESSION_CONFLICT:521,SESSION_TIMEOUT:522,SESSION_CLOSED:523,CLIENT_BAD_REQUEST:768,CLIENT_UNAUTHORIZED:769,CLIENT_FORBIDDEN:771,CLIENT_TIMEOUT:776,CLIENT_OVERRUN:781,CLIENT_BAD_TYPE:783,CLIENT_TOO_MANY:797};
Guacamole.Status.Code.fromHTTPCode=function(b){switch(b){case 400:return Guacamole.Status.Code.CLIENT_BAD_REQUEST;case 403:return Guacamole.Status.Code.CLIENT_FORBIDDEN;case 404:return Guacamole.Status.Code.RESOURCE_NOT_FOUND;case 429:return Guacamole.Status.Code.CLIENT_TOO_MANY;case 503:return Guacamole.Status.Code.SERVER_BUSY}return Guacamole.Status.Code.SERVER_ERROR};
Guacamole.Status.Code.fromWebSocketCode=function(b){switch(b){case 1E3:return Guacamole.Status.Code.SUCCESS;case 1006:case 1015:return Guacamole.Status.Code.UPSTREAM_NOT_FOUND;case 1001:case 1012:case 1013:case 1014:return Guacamole.Status.Code.UPSTREAM_UNAVAILABLE}return Guacamole.Status.Code.SERVER_ERROR};Guacamole=Guacamole||{};
Guacamole.StringReader=function(b){var a=this,d=new Guacamole.UTF8Parser;b=new Guacamole.ArrayBufferReader(b);b.ondata=function(b){b=d.decode(b);if(a.ontext)a.ontext(b)};b.onend=function(){if(a.onend)a.onend()};this.onend=this.ontext=null};Guacamole=Guacamole||{};
Guacamole.StringWriter=function(b){function a(b){if(127>=b){var c=0;var d=1}else if(2047>=b)c=192,d=2;else if(65535>=b)c=224,d=3;else if(2097151>=b)c=240,d=4;else{a(65533);return}var e=d;if(h+e>=f.length){var l=new Uint8Array(2*(h+e));l.set(f);f=l}h+=e;e=h-1;for(l=1;l<d;l++)f[e--]=128|b&63,b>>=6;f[e]=c|b}function d(b){for(var c=0;c<b.length;c++){var d=b.charCodeAt(c);a(d)}if(0<h)return b=f.subarray(0,h),h=0,b}var c=this,e=new Guacamole.ArrayBufferWriter(b),f=new Uint8Array(8192),h=0;e.onack=function(a){if(c.onack)c.onack(a)};
this.sendText=function(a){a.length&&e.sendData(d(a))};this.sendEnd=function(){e.sendEnd()};this.onack=null};Guacamole=Guacamole||{};
Guacamole.Touch=function(b){Guacamole.Event.Target.call(this);var a=this,d=Math.floor(16*window.devicePixelRatio);this.touches={};this.activeTouches=0;b.addEventListener("touchstart",function(c){for(var e=0;e<c.changedTouches.length;e++){var f=c.changedTouches[e],h=f.identifier;a.touches[h]||(h=a.touches[h]=new Guacamole.Touch.State({id:h,radiusX:f.radiusX||d,radiusY:f.radiusY||d,angle:f.angle||0,force:f.force||1}),a.activeTouches++,h.fromClientPosition(b,f.clientX,f.clientY),a.dispatch(new Guacamole.Touch.Event("touchmove",
c,h)))}},!1);b.addEventListener("touchmove",function(c){for(var e=0;e<c.changedTouches.length;e++){var f=c.changedTouches[e],h=a.touches[f.identifier];h&&(f.force&&(h.force=f.force),h.angle=f.angle||0,h.radiusX=f.radiusX||d,h.radiusY=f.radiusY||d,h.fromClientPosition(b,f.clientX,f.clientY),a.dispatch(new Guacamole.Touch.Event("touchmove",c,h)))}},!1);b.addEventListener("touchend",function(c){for(var d=0;d<c.changedTouches.length;d++){var f=c.changedTouches[d],h=f.identifier,l=a.touches[h];l&&(delete a.touches[h],
a.activeTouches--,l.force=0,l.fromClientPosition(b,f.clientX,f.clientY),a.dispatch(new Guacamole.Touch.Event("touchend",c,l)))}},!1)};Guacamole.Touch.State=function(b){b=b||{};Guacamole.Position.call(this,b);this.id=b.id||0;this.radiusX=b.radiusX||0;this.radiusY=b.radiusY||0;this.angle=b.angle||0;this.force=b.force||1};Guacamole.Touch.Event=function(b,a,d){Guacamole.Event.DOMEvent.call(this,b,[a]);this.state=d};Guacamole=Guacamole||{};
Guacamole.Tunnel=function(){this.connect=function(b){};this.disconnect=function(){};this.sendMessage=function(b){};this.setState=function(b){if(b!==this.state&&(this.state=b,this.onstatechange))this.onstatechange(b)};this.setUUID=function(b){this.uuid=b;if(this.onuuid)this.onuuid(b)};this.isConnected=function(){return this.state===Guacamole.Tunnel.State.OPEN||this.state===Guacamole.Tunnel.State.UNSTABLE};this.state=Guacamole.Tunnel.State.CLOSED;this.receiveTimeout=15E3;this.unstableThreshold=1500;
this.oninstruction=this.onstatechange=this.onerror=this.onuuid=this.uuid=null};Guacamole.Tunnel.INTERNAL_DATA_OPCODE="";Guacamole.Tunnel.State={CONNECTING:0,OPEN:1,CLOSED:2,UNSTABLE:3};
Guacamole.HTTPTunnel=function(b,a,d){function c(a,b){for(var c in b)a.setRequestHeader(c,b[c])}function e(a){window.clearTimeout(y);window.clearTimeout(u);window.clearInterval(C);if(m.state!==Guacamole.Tunnel.State.CLOSED){if(a.code!==Guacamole.Status.Code.SUCCESS&&m.onerror&&(m.state===Guacamole.Tunnel.State.CONNECTING||a.code!==Guacamole.Status.Code.RESOURCE_NOT_FOUND))m.onerror(a);v=!1;m.setState(Guacamole.Tunnel.State.CLOSED)}}function f(){if(m.isConnected())if(0<x.length){v=!0;var a=new XMLHttpRequest;
a.open("POST",r+m.uuid);a.withCredentials=t;c(a,D);a.setRequestHeader("Content-type","application/octet-stream");a.setRequestHeader("Guacamole-Tunnel-Token",A);a.onreadystatechange=function(){4===a.readyState&&(B(),200!==a.status?h(a):f())};a.send(x);x=""}else v=!1}function h(a){var b=parseInt(a.getResponseHeader("Guacamole-Status-Code"));b?(a=a.getResponseHeader("Guacamole-Error-Message"),e(new Guacamole.Status(b,a))):a.status?e(new Guacamole.Status(Guacamole.Status.Code.fromHTTPCode(a.status),a.statusText)):
e(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_NOT_FOUND))}function l(a){function b(){if(!m.isConnected())null!==c&&clearInterval(c);else if(!(2>a.readyState)){try{var f=a.status}catch(G){f=200}d||200!==f||(d=n());if(3===a.readyState||4===a.readyState)if(B(),1===q&&(3!==a.readyState||c?4===a.readyState&&c&&clearInterval(c):c=setInterval(b,30)),0===a.status)m.disconnect();else if(200!==a.status)h(a);else{try{var l=a.responseText}catch(G){return}try{g.receive(l,!0)}catch(G){e(new Guacamole.Status(Guacamole.Status.Code.SERVER_ERROR,
G.message))}}}}var c=null,d=null,f=0,g=new Guacamole.Parser;g.oninstruction=function N(b,e){if(b===Guacamole.Tunnel.INTERNAL_DATA_OPCODE&&0===e.length)g=new Guacamole.Parser,g.oninstruction=N,c&&clearInterval(c),a.onreadystatechange=null,a.abort(),d&&l(d);else if(b!==Guacamole.Tunnel.INTERNAL_DATA_OPCODE&&m.oninstruction)m.oninstruction(b,e)};a.onreadystatechange=1===q?function(){3===a.readyState&&(f++,2<=f&&(q=0,a.onreadystatechange=b));b()}:b;b()}function n(){var a=new XMLHttpRequest;a.open("GET",
k+m.uuid+":"+p++);a.setRequestHeader("Guacamole-Tunnel-Token",A);a.withCredentials=t;c(a,D);a.send(null);return a}var m=this,g=b+"?connect",k=b+"?read:",r=b+"?write:",q=1,v=!1,x="",t=!!a,y=null,u=null,C=null,D=d||{},A=null,B=function(){window.clearTimeout(y);window.clearTimeout(u);m.state===Guacamole.Tunnel.State.UNSTABLE&&m.setState(Guacamole.Tunnel.State.OPEN);y=window.setTimeout(function(){e(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_TIMEOUT,"Server timeout."))},m.receiveTimeout);u=window.setTimeout(function(){m.setState(Guacamole.Tunnel.State.UNSTABLE)},
m.unstableThreshold)};this.sendMessage=function(){m.isConnected()&&arguments.length&&(x+=Guacamole.Parser.toInstruction(arguments),v||f())};var p=0;this.connect=function(a){B();m.setState(Guacamole.Tunnel.State.CONNECTING);var b=new XMLHttpRequest;b.onreadystatechange=function(){4===b.readyState&&(200!==b.status?h(b):(B(),m.setUUID(b.responseText),(A=b.getResponseHeader("Guacamole-Tunnel-Token"))?(m.setState(Guacamole.Tunnel.State.OPEN),C=setInterval(function(){m.sendMessage("nop")},500),l(n())):
e(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_NOT_FOUND))))};b.open("POST",g,!0);b.withCredentials=t;c(b,D);b.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset\x3dUTF-8");b.send(a)};this.disconnect=function(){e(new Guacamole.Status(Guacamole.Status.Code.SUCCESS,"Manually closed."))}};Guacamole.HTTPTunnel.prototype=new Guacamole.Tunnel;
Guacamole.WebSocketTunnel=function(b){function a(a){window.clearTimeout(f);window.clearTimeout(h);window.clearTimeout(l);if(d.state!==Guacamole.Tunnel.State.CLOSED){if(a.code!==Guacamole.Status.Code.SUCCESS&&d.onerror)d.onerror(a);d.setState(Guacamole.Tunnel.State.CLOSED);e.close()}}var d=this,c=null,e=null,f=null,h=null,l=null,n={"http:":"ws:","https:":"wss:"},m=0;if("ws:"!==b.substring(0,3)&&"wss:"!==b.substring(0,4))if(n=n[window.location.protocol],"/"===b.substring(0,1))b=n+"//"+window.location.host+
b;else{var g=window.location.pathname.lastIndexOf("/");g=window.location.pathname.substring(0,g+1);b=n+"//"+window.location.host+g+b}var k=function(){var a=(new Date).getTime();d.sendMessage(Guacamole.Tunnel.INTERNAL_DATA_OPCODE,"ping",a);m=a},r=function(){window.clearTimeout(f);window.clearTimeout(h);window.clearTimeout(l);d.state===Guacamole.Tunnel.State.UNSTABLE&&d.setState(Guacamole.Tunnel.State.OPEN);f=window.setTimeout(function(){a(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_TIMEOUT,
"Server timeout."))},d.receiveTimeout);h=window.setTimeout(function(){d.setState(Guacamole.Tunnel.State.UNSTABLE)},d.unstableThreshold);var b=(new Date).getTime();b=Math.max(m+500-b,0);0<b?l=window.setTimeout(k,b):k()};this.sendMessage=function(a){d.isConnected()&&arguments.length&&e.send(Guacamole.Parser.toInstruction(arguments))};this.connect=function(f){r();d.setState(Guacamole.Tunnel.State.CONNECTING);c=new Guacamole.Parser;c.oninstruction=function(a,b){null===d.uuid&&(a===Guacamole.Tunnel.INTERNAL_DATA_OPCODE&&
1===b.length&&d.setUUID(b[0]),d.setState(Guacamole.Tunnel.State.OPEN));if(a!==Guacamole.Tunnel.INTERNAL_DATA_OPCODE&&d.oninstruction)d.oninstruction(a,b)};e=new WebSocket(b+"?"+f,"guacamole");e.onopen=function(a){r()};e.onclose=function(b){b.reason?a(new Guacamole.Status(parseInt(b.reason),b.reason)):b.code?a(new Guacamole.Status(Guacamole.Status.Code.fromWebSocketCode(b.code))):a(new Guacamole.Status(Guacamole.Status.Code.UPSTREAM_NOT_FOUND))};e.onmessage=function(b){r();try{c.receive(b.data)}catch(x){a(new Guacamole.Status(Guacamole.Status.Code.SERVER_ERROR,
x.message))}}};this.disconnect=function(){a(new Guacamole.Status(Guacamole.Status.Code.SUCCESS,"Manually closed."))}};Guacamole.WebSocketTunnel.prototype=new Guacamole.Tunnel;
Guacamole.ChainedTunnel=function(b){function a(b){function h(){b.onstatechange=d.onstatechange;b.oninstruction=d.oninstruction;b.onerror=d.onerror;b.uuid&&d.setUUID(b.uuid);b.onuuid=function(a){d.setUUID(a)};f=b}d.disconnect=b.disconnect;d.sendMessage=b.sendMessage;var l=function(c){if(c&&c.code===Guacamole.Status.Code.UPSTREAM_TIMEOUT)return e=[],null;if(c=e.shift())b.onerror=null,b.oninstruction=null,b.onstatechange=null,a(c);return c};b.onstatechange=function(a){switch(a){case Guacamole.Tunnel.State.OPEN:h();
if(d.onstatechange)d.onstatechange(a);break;case Guacamole.Tunnel.State.CLOSED:if(!l()&&d.onstatechange)d.onstatechange(a)}};b.oninstruction=function(a,b){h();if(d.oninstruction)d.oninstruction(a,b)};b.onerror=function(a){if(!l(a)&&d.onerror)d.onerror(a)};b.connect(c)}for(var d=this,c,e=[],f=null,h=0;h<arguments.length;h++)e.push(arguments[h]);this.connect=function(b){c=b;if(b=f?f:e.shift())a(b);else if(d.onerror)d.onerror(Guacamole.Status.Code.SERVER_ERROR,"No tunnels to try.")}};
Guacamole.ChainedTunnel.prototype=new Guacamole.Tunnel;
Guacamole.StaticHTTPTunnel=function(b,a,d){var c=this,e=null,f=d||{};this.size=null;this.sendMessage=function(a){};this.connect=function(d){c.disconnect();c.setState(Guacamole.Tunnel.State.CONNECTING);var h=new Guacamole.Parser,n=new Guacamole.UTF8Parser;h.oninstruction=function(a,b){if(c.oninstruction)c.oninstruction(a,b)};e=new AbortController;fetch(b,{headers:f,credentials:a?"include":"same-origin",signal:e.signal}).then(function(a){if(a.ok){c.size=a.headers.get("Content-Length");c.setState(Guacamole.Tunnel.State.OPEN);
var b=a.body.getReader();b.read().then(function q(a){a.done?c.disconnect():(h.receive(n.decode(a.value)),b.read().then(q))})}else{if(c.onerror)c.onerror(new Guacamole.Status(Guacamole.Status.Code.fromHTTPCode(a.status),a.statusText));c.disconnect()}})};this.disconnect=function(){e&&(e.abort(),e=null);c.setState(Guacamole.Tunnel.State.CLOSED)}};Guacamole.StaticHTTPTunnel.prototype=new Guacamole.Tunnel;Guacamole=Guacamole||{};
Guacamole.UTF8Parser=function(){var b=0,a=0;this.decode=function(d){var c="";d=new Uint8Array(d);for(var e=0;e<d.length;e++){var f=d[e];0===b?127===(f|127)?c+=String.fromCharCode(f):223===(f|31)?(a=f&31,b=1):239===(f|15)?(a=f&15,b=2):247===(f|7)?(a=f&7,b=3):c+="�":191===(f|63)?(a=a<<6|f&63,b--,0===b&&(c+=String.fromCharCode(a))):(b=0,c+="�")}return c}};Guacamole=Guacamole||{};Guacamole.API_VERSION="1.6.0";Guacamole=Guacamole||{};Guacamole.VideoPlayer=function(){this.sync=function(){}};
Guacamole.VideoPlayer.isSupportedType=function(b){return!1};Guacamole.VideoPlayer.getSupportedTypes=function(){return[]};Guacamole.VideoPlayer.getInstance=function(b,a,d){return null};
GUACJS_EOF
}

gui_possible() { # a desktop session, Python and a browser are all that is needed
  command -v python3 >/dev/null || return 1
  [[ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]] || return 1
  command -v xdg-open >/dev/null || command -v chromium >/dev/null || command -v google-chrome-stable >/dev/null || command -v firefox >/dev/null
}

gui_url() { python3 -I -c 'import json,sys; d=json.load(open(sys.argv[1])); print("http://127.0.0.1:%d/?t=%s" % (d["port"], d["token"]))' "$GUI_INFO" 2>/dev/null; }
gui_alive() { # the server answers on its port
  [[ -f "$GUI_INFO" ]] || return 1
  local port; port="$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))["port"])' "$GUI_INFO" 2>/dev/null)"
  [[ -n "$port" ]] && timeout 3 bash -c "exec 3<>/dev/tcp/127.0.0.1/$port" 2>/dev/null
}

gui_window_open() { # a DeckVM app window is already on screen: its browser process carries --class=DeckVM
  pgrep -f -- '--class=DeckVM' >/dev/null 2>&1
}

# Ask the desktop to bring the DeckVM window to the front (KDE: a tiny KWin script; elsewhere: xdotool/kdotool/wmctrl).
raise_gui_window() {
  local js="$BASE/raise.js" name="deckvm-raise" id g
  cat > "$js" <<'JSEOF'
(function () {
  var list = (typeof workspace.windowList === "function") ? workspace.windowList() : workspace.clientList();
  for (var i = 0; i < list.length; i++) {
    var w = list[i];
    if (w.caption && /^DeckVM/.test(w.caption)) {
      if (typeof workspace.activeWindow !== "undefined") { workspace.activeWindow = w; } else { workspace.activeClient = w; }
    }
  }
})();
JSEOF
  if command -v gdbus >/dev/null 2>&1; then
    g="$(gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.loadScript "$js" "$name" 2>/dev/null)"
    id="$(sed -n 's/^(\(-\?[0-9]\+\),)$/\1/p' <<<"$g")"
    if [[ -n "$id" && "$id" != -1 ]]; then
      gdbus call --session --dest org.kde.KWin --object-path "/Scripting/Script$id" --method org.kde.kwin.Script.run >/dev/null 2>&1
      sleep 0.5
      gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.unloadScript "$name" >/dev/null 2>&1
      return 0
    fi
  fi
  if command -v kdotool >/dev/null 2>&1; then kdotool search --name '^DeckVM' windowactivate >/dev/null 2>&1 && return 0; fi
  if command -v xdotool >/dev/null 2>&1; then xdotool search --name '^DeckVM' windowactivate >/dev/null 2>&1 && return 0; fi
  if command -v wmctrl >/dev/null 2>&1; then wmctrl -a DeckVM >/dev/null 2>&1 && return 0; fi
  return 0
}

open_gui_window() {
  # The Deck screen is 1280x800 and the taskbar and title bar use about 80 pixels of it, so a 1280x800 window cannot fit.
  # Start maximised; the size and position are the fallback if the desktop ignores that.
  local url="$1" b app opened=0
  [[ "${DECKVM_NO_WINDOW:-0}" == 1 ]] && return 0      # the self-test talks to the window server without opening a window
  # A Chromium-style browser can show DeckVM as its own app window; anything else gets a normal tab.
  for b in chromium chromium-browser google-chrome-stable google-chrome brave-browser microsoft-edge-stable; do
    if command -v "$b" >/dev/null 2>&1; then
      # Its own profile makes this a separate browser from your normal one. Otherwise the window is handed to a Chrome that is
      # already open, which ignores --class (so the taskbar guesses a name and icon) and shares its processes with your tabs.
      ( setsid nohup "$b" --user-data-dir="$BASE/chrome-profile" --no-first-run --no-default-browser-check --class=DeckVM --app="$url" --start-maximized --window-position=0,0 --window-size=1280,690 >/dev/null 2>&1 & ); opened=1; break
    fi
  done
  # Browsers installed from Discover (Flatpak) are not on the PATH under those names
  if [[ $opened == 0 ]] && command -v flatpak >/dev/null 2>&1; then
    for app in com.google.Chrome org.chromium.Chromium com.brave.Browser com.microsoft.Edge; do
      if flatpak info "$app" >/dev/null 2>&1; then
        ( setsid nohup flatpak run "$app" --user-data-dir="$HOME/.var/app/$app/config/deckvm-profile" --no-first-run --no-default-browser-check --class=DeckVM --app="$url" --start-maximized --window-position=0,0 --window-size=1280,690 >/dev/null 2>&1 & ); opened=1; break
      fi
    done
  fi
  if [[ $opened == 0 ]] && command -v xdg-open >/dev/null 2>&1; then ( setsid nohup xdg-open "$url" >/dev/null 2>&1 & ); opened=1; fi
  [[ $opened == 1 ]] || return 1
  ( sleep 2; raise_gui_window ) >/dev/null 2>&1 &
  return 0
}

cmd_selftest() { # selftest [quick|lifecycle|full|usb|all] [--yes-delete] [--win=CODE]: runs DeckVM through its own window back end and reports
  NOLOG=1
  persist_self
  mkdir -p "$LOGS"
  write_gui_py
  write_askpass
  cat > "$BASE/selftest.py" <<'SELFTEST_EOF'
#!/usr/bin/env python3
# NerdZap DeckVM self-test. Runs DeckVM through the same window back end the DeckVM window uses, checks the
# result of every step, and writes one report. Usage: deckvm.sh selftest [quick|lifecycle|full|usb] [--yes-delete]
import glob, http.cookiejar, json, os, re, subprocess, sys, time, urllib.error, urllib.request

BASE, SELF = sys.argv[1], sys.argv[2]
LEVELS = [a for a in sys.argv[3:] if not a.startswith("--")] or ["quick"]
FLAGS = [a for a in sys.argv[3:] if a.startswith("--")]
YES_DELETE = "--yes-delete" in FLAGS
EDITION = next((f.split("=", 1)[1] for f in FLAGS if f.startswith("--win=")), "tiny11")
STAMP = time.strftime("%Y%m%d-%H%M%S")
OUT = os.path.join(BASE, "selftest-%s.txt" % STAMP)
SERIES = os.path.join(BASE, "selftest-%s-series.csv" % STAMP)
ENV = dict(os.environ, DECKVM_BASE=BASE, DECKVM_NO_WINDOW="1")
T0 = time.time()
RES = []          # (status, name, detail)
NOTES = []


def say(s):
    print(s, flush=True)
    with open(OUT, "a") as f:
        f.write(s + "\n")


def result(status, name, detail=""):
    RES.append((status, name, detail))
    say("  [%s] %s%s" % (status, name, (" - " + detail) if detail else ""))


def ok(name, detail=""):
    result("PASS", name, detail)


def bad(name, detail=""):
    result("FAIL", name, detail)


def warn(name, detail=""):
    result("WARN", name, detail)


def check(cond, name, detail_ok="", detail_bad=""):
    (ok if cond else bad)(name, detail_ok if cond else detail_bad)
    return cond


def note(s):
    NOTES.append(s)
    say("  note: " + s)


def head(s):
    say("")
    say("=== %s (%ds) ===" % (s, time.time() - T0))


def sh(cmd, timeout=60, env=None):
    try:
        r = subprocess.run(cmd, shell=isinstance(cmd, str), capture_output=True, text=True, timeout=timeout,
                           env=env or ENV, stdin=subprocess.DEVNULL)
        return r.returncode, (r.stdout + r.stderr).strip()
    except subprocess.TimeoutExpired:
        return 124, "(timed out after %ds)" % timeout


def kv(text):
    d = {}
    for ln in text.splitlines():
        if "=" in ln:
            k, v = ln.split("=", 1)
            d[k.strip()] = v.strip()
    return d


def status():
    return kv(sh(["bash", SELF, "status-kv"], 40)[1])


def helpers():
    rc, out = sh("pgrep -af ' _watch(_usb|_kernel|dog)( .*)?$' | grep -v pgrep", 10)
    return [ln for ln in out.splitlines() if ln.strip()] if rc == 0 else []


# ------------------------------------------------------------------ gui api ----
class Api:
    def __init__(self):
        self.root = None
        self.op = None

    def start(self):
        info_path = os.path.join(BASE, "gui.json")
        reused = False
        try:
            reused = os.path.exists(info_path) and sh(["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/%d" % json.load(open(info_path))["port"]], 5)[0] == 0
        except (OSError, ValueError, KeyError):
            pass
        t = time.time()
        rc, out = sh(["bash", SELF, "gui"], 60)
        if rc != 0:
            bad("DeckVM window server starts", out[-300:])
            return False
        info = json.load(open(info_path))
        self.root = "http://127.0.0.1:%d" % info["port"]
        cj = http.cookiejar.CookieJar()
        self.op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
        self.op.open("%s/?t=%s" % (self.root, info["token"]), timeout=10).read()
        ok("DeckVM window server %s" % ("was already running" if reused else "starts"), "%.1fs" % (time.time() - t))
        return True

    def get(self, p, timeout=15):
        return json.load(self.op.open(self.root + p, timeout=timeout))

    def post(self, p, body):
        rq = urllib.request.Request(self.root + p, data=json.dumps(body).encode(), headers={"X-DeckVM": "1", "Content-Type": "application/json"})
        try:
            return json.load(self.op.open(rq, timeout=30))
        except urllib.error.HTTPError as e:
            try:
                return json.load(e)
            except ValueError:
                return {"ok": False, "error": "HTTP %d" % e.code}

    def state(self):
        return self.get("/api/state")

    def quit(self):
        try:
            self.post("/api/quit", {})
        except Exception:
            pass


A = Api()


def wait_job(name, timeout, poll=1.0, series=None):
    """Wait for the window's current job to end. Returns the final state (or the last one seen on timeout)."""
    t0 = time.time()
    s = None
    while time.time() - t0 < timeout:
        try:
            s = A.state()
        except Exception as e:
            time.sleep(poll)
            continue
        if series is not None:
            series(s)
        j = s.get("job")
        if j and j["name"] == name and not j["running"]:
            return s
        time.sleep(poll)
    return s


def run_job(name, body=None, timeout=180, series=None):
    b = {"name": name}
    b.update(body or {})
    t = time.time()
    r = A.post("/api/job", b)
    if not r.get("ok"):
        bad("job '%s' accepted" % name, r.get("error", ""))
        return None, 0
    s = wait_job(name, timeout, series=series)
    el = time.time() - t
    j = (s or {}).get("job") or {}
    if j.get("running") or j.get("name") != name:
        bad("job '%s' finishes" % name, "still running after %ds" % timeout)
    return s, el


def job_summary(s):
    j = (s or {}).get("job") or {}
    return "rc=%s %s" % (j.get("rc"), " | ".join((j.get("tail") or [])[-3:]))[:300]


# --------------------------------------------------------------------- quick ----
KEYS = ["version", "installed", "edition", "vm", "web", "engine", "usb_session", "driver_block", "free_gb", "rootless", "stage", "ram", "cores", "disk"]


def quick():
    head("QUICK: this Deck and DeckVM's own state (changes nothing)")
    osr = kv(open("/etc/os-release").read().replace('"', "")) if os.path.exists("/etc/os-release") else {}
    note("system: %s %s, kernel %s, python %s" % (osr.get("NAME", "?"), osr.get("VERSION_ID", osr.get("BUILD_ID", "")), os.uname().release, sys.version.split()[0]))
    note("podman: %s" % sh("podman --version", 10)[1])
    note("memory: %s" % sh("free -g | awk 'NR==2{print $2\" GB total, \"$7\" GB available\"}'", 10)[1])
    note("desktop: DISPLAY=%s WAYLAND_DISPLAY=%s" % (os.environ.get("DISPLAY", ""), os.environ.get("WAYLAND_DISPLAY", "")))
    check(os.path.exists("/dev/kvm"), "Hardware virtualisation (KVM) present", "", "/dev/kvm is missing")
    check(os.access("/dev/kvm", os.R_OK | os.W_OK), "KVM usable by your user", "", "no permission on /dev/kvm")
    st = status()
    missing = [k for k in KEYS if k not in st]
    check(not missing, "status has every field the window needs", "%d fields" % len(st), "missing: %s" % ", ".join(missing))
    if st.get("free_gb", "").isdigit():
        check(int(st["free_gb"]) >= 30, "free disk space", "%s GB free" % st["free_gb"], "only %s GB free" % st["free_gb"])
    # leftovers that cause the 'same bug again' problems
    vm = st.get("vm", "")
    hp = helpers()
    if vm != "running":
        check(not hp, "no stray helper programs while Windows is off", "", "left running: " + "; ".join(h[:90] for h in hp))
        check(st.get("engine", "") != "root", "no stale 'administrator mode' record while Windows is off", "", "engine=root is left over from an old session")
        check(st.get("driver_block", "0") == "0", "SteamOS controller drivers are not blocked while Windows is off", "", "driver_block=1: SteamOS's Xbox drivers are still switched off")
        check(st.get("usb_session", "0") == "0", "no USB session recorded while Windows is off", "", "usb_session=1 but Windows is not running")
    else:
        note("Windows is running now; the 'while off' leftovers checks were skipped")
    rc, out = sh("ls -la /etc/modprobe.d/zz-deckvm.conf 2>&1 | head -1", 5)
    note("modprobe file: " + out[:120])
    # the window server and every page it serves
    if A.start():
        t = time.time()
        try:
            s = A.state()
            check(all(k in s for k in ("status", "job", "now")), "window state answers", "%.2fs" % (time.time() - t), "missing fields: " + ",".join(s.keys()))
            check(time.time() - t < 3, "window state is quick (under 3 s)", "", "took %.1fs" % (time.time() - t))
        except Exception as e:
            bad("window state answers", str(e))
        for p in ("/api/devices", "/api/log?from=0", "/api/winlog", "/api/report"):
            try:
                A.get(p, 40)
                ok("window page %s answers" % p)
            except Exception as e:
                bad("window page %s answers" % p, str(e))
        try:
            urllib.request.urlopen(A.root + "/api/state", timeout=5)
            bad("window refuses callers without the key")
        except urllib.error.HTTPError as e:
            check(e.code == 403, "window refuses callers without the key", "403", "HTTP %d" % e.code)
        except Exception as e:
            bad("window refuses callers without the key", str(e))
        try:
            devs = A.get("/api/devices")["devices"]
            note("USB devices: " + ("; ".join("%s %s %s%s" % (d["port"], d["id"], d["name"], " (internal)" if d.get("internal") else "") for d in devs) or "none"))
        except Exception:
            pass
    # the report
    before = set(glob.glob(os.path.join(BASE, "report-*.txt")))
    rc, out = sh(["bash", SELF, "report"], 180)
    after = sorted(set(glob.glob(os.path.join(BASE, "report-*.txt"))) - before) or sorted(glob.glob(os.path.join(BASE, "report-*.txt")))[-1:]
    if check(bool(after), "report is made", os.path.basename(after[-1]) if after else "", "no report file: " + out[-200:]):
        txt = open(after[-1], errors="replace").read()
        for sec in ("WINDOW (gui.log", "TOOLS and VERSIONS", "COMMANDS log"):
            check(sec in txt, "report has the '%s' section" % sec.split(" (")[0])
        pw = ""
        try:
            pw = re.search(r"^WIN_PASS=\"?([^\"\n]+)", open(os.path.join(BASE, "config.env")).read(), re.M).group(1)
        except (OSError, AttributeError):
            pass
        if pw:
            check(pw not in txt, "report hides the Windows password", "", "the Windows password appears in the report")


# ----------------------------------------------------------------- lifecycle ----
def lifecycle(cycles=2):
    head("LIFECYCLE: start and stop Windows %d times, checking everything after each step" % cycles)
    st = status()
    if st.get("installed") != "1":
        warn("lifecycle skipped", "Windows is not set up yet (run the 'full' level, or set it up first)")
        return
    if not A.root and not A.start():
        return
    if st.get("vm") == "running":
        s, el = run_job("stop", timeout=180)
        check(status().get("vm") != "running", "stopped Windows that was already running", "%.0fs" % el, "still running: " + job_summary(s))
    for n in range(1, cycles + 1):
        say("  -- cycle %d" % n)
        samples = []

        def grab(s, samples=samples):
            samples.append((time.time(), s))

        s, el = run_job("start", timeout=240, series=grab)
        j = (s or {}).get("job") or {}
        check(j.get("rc") == 0, "cycle %d: start job succeeds" % n, "%.0fs" % el, job_summary(s))
        # Windows' web screen should come up shortly after
        t = time.time()
        web = False
        while time.time() - t < 120:
            st = status()
            if st.get("vm") == "running" and A.state()["status"].get("web") == "1":
                web = True
                break
            time.sleep(2)
        check(web, "cycle %d: Windows is running and its screen is reachable" % n, "after %.0fs" % (time.time() - t), "no screen after 120 s")
        check(st.get("engine", "") != "root", "cycle %d: normal (no-password) mode is in use" % n, "", "engine=%s" % st.get("engine"))
        check(st.get("driver_block", "0") == "0", "cycle %d: SteamOS drivers untouched" % n, "", "driver_block=1")
        have_inh = sh("systemd-inhibit --what=sleep --who=DeckVMSelftest --why=test true", 10)[0] == 0
        if have_inh:
            rc, out = sh("pgrep -af 'systemd-inhibit.*NerdZapDeckVM' | grep -v pgrep", 10)
            check(rc == 0, "cycle %d: sleep blocker is on while Windows runs" % n, "", "no sleep blocker found")
        # the window must agree with the script
        a = A.state()["status"]
        check(a.get("vm") == st.get("vm") and a.get("installed") == st.get("installed"), "cycle %d: window and script agree on the state" % n, "", "window says vm=%s installed=%s, script says vm=%s installed=%s" % (a.get("vm"), a.get("installed"), st.get("vm"), st.get("installed")))
        time.sleep(10)
        s, el = run_job("stop", timeout=240)
        j = (s or {}).get("job") or {}
        check(j.get("rc") == 0, "cycle %d: stop job succeeds" % n, "%.0fs" % el, job_summary(s))
        st = status()
        check(st.get("vm") in ("none", "exited", "stopped", ""), "cycle %d: Windows is really off" % n, st.get("vm"), "vm=%s" % st.get("vm"))
        time.sleep(2)
        check(A.state()["status"].get("web") == "0", "cycle %d: Windows screen is gone" % n, "", "port 8006 still busy")
        hp = helpers()
        check(not hp, "cycle %d: no helper programs left behind" % n, "", "; ".join(h[:90] for h in hp))
        if have_inh:
            rc, out = sh("pgrep -af 'systemd-inhibit.*NerdZapDeckVM' | grep -v pgrep", 10)
            check(rc != 0, "cycle %d: sleep blocker is released" % n, "", "still held: " + out[:120])
        check(st.get("engine", "") != "root" and st.get("driver_block", "0") == "0", "cycle %d: state is clean afterwards" % n, "", "engine=%s driver_block=%s" % (st.get("engine"), st.get("driver_block")))


# ---------------------------------------------------------------------- full ----
class Watch:
    """Records every progress reading the window would have shown, then looks for the things that confused you."""

    def __init__(self):
        self.rows = []
        open(SERIES, "w").write("t,stage,step,pct,bytes,total,speed,eta_shown,prep,booted,parts,job_running\n")

    def __call__(self, s):
        p = s.get("progress") or {}
        j = s.get("job") or {}
        b, tot, sp = p.get("bytes"), p.get("total"), p.get("speed") or 0
        eta = bool(tot and b is not None and sp > 0 and tot > b)    # same rule the window uses to show 'time left'
        row = (round(time.time() - T0, 1), s.get("stage", ""), (j.get("step") or "")[:40], p.get("pct"), b, tot, sp, int(eta),
               int(bool(p.get("prep"))), int(bool(p.get("booted"))), (p.get("pull") or {}).get("parts"), int(bool(j.get("running"))))
        self.rows.append(row)
        with open(SERIES, "a") as f:
            f.write(",".join("" if v is None else str(v).replace(",", ";") for v in row) + "\n")

    def analyse(self, label):
        dl = [r for r in self.rows if r[4] is not None and not r[8] and not r[9]]
        if len(dl) < 5:
            note("%s: too few download readings to judge (%d)" % (label, len(dl)))
            return
        back = [(a, b) for a, b in zip(dl, dl[1:]) if b[4] < a[4] * 0.99]
        check(not back, "%s: downloaded figure never goes backwards" % label, "", ("%d times (e.g. %s then %s)" % (len(back), back[0][0][4], back[0][1][4])) if back else "")
        flips = sum(1 for a, b in zip(dl, dl[1:]) if a[7] != b[7] and b[4] < (b[5] or 1) * 0.97)
        check(flips <= 2, "%s: 'time left' does not flicker" % label, "%d changes" % flips, "%d times it appeared/disappeared" % flips)
        zero = [r for r in dl if r[6] == 0 and r[4] and r[4] > 50_000_000]
        check(len(zero) <= 3, "%s: speed does not drop to zero while downloading" % label, "", "%d readings of zero speed" % len(zero))
        jumps = [(a, b) for a, b in zip(dl, dl[1:]) if a[3] is not None and b[3] is not None and b[3] - a[3] > 15]
        check(not jumps, "%s: percentage moves smoothly" % label, "", "%d jumps of more than 15 points" % len(jumps))
        longest = 0
        last_change = dl[0][0]
        for a, b in zip(dl, dl[1:]):
            if b[4] != a[4]:
                last_change = b[0]
            longest = max(longest, b[0] - last_change)
        check(longest < 45, "%s: the figure never sits still for 45 s" % label, "longest %ds" % longest, "stood still for %ds" % longest)
        stages = [r[1] for r in self.rows if r[1]]
        order = ["", "check", "pull", "install", "ready"]
        seen = [order.index(x) for x in stages if x in order]
        check(seen == sorted(seen), "%s: setup steps only move forward" % label, "", "steps went backwards: %s" % ",".join(dict.fromkeys(stages)))


def storage_state():
    root = os.path.join(BASE, "storage")
    names = []
    for dp, dn, fn in os.walk(root):
        for f in fn:
            names.append(os.path.relpath(os.path.join(dp, f), root))
    return names


def wait_download(w, minbytes, timeout):
    t = time.time()
    while time.time() - t < timeout:
        try:
            s = A.state()
        except Exception:
            time.sleep(2)
            continue
        w(s)
        p = s.get("progress") or {}
        if (p.get("bytes") or 0) >= minbytes:
            return s
        j = s.get("job") or {}
        if not j.get("running"):
            return s
        time.sleep(2)
    return None


def full():
    head("FULL: set Windows up from nothing, cancel it two ways, then set it up for real")
    if not YES_DELETE:
        bad("full level needs permission", "it deletes your current Windows. Run again with --yes-delete if that is fine.")
        return
    if not A.root and not A.start():
        return
    s0 = status()
    if s0.get("vm") == "running":
        run_job("stop", timeout=240)
    s, el = run_job("reset", timeout=180)
    check(((s or {}).get("job") or {}).get("rc") == 0, "old Windows deleted", "%.0fs" % el, job_summary(s))
    check(not [n for n in storage_state() if n.startswith("data.")], "no Windows disk left after delete", "", "files: %s" % ",".join(storage_state())[:200])
    body = {"opts": {"win": EDITION, "ram": 6, "cores": 4, "disk": 40, "xboxapp": False}}

    # 1. start, wait for the download to get going, cancel and KEEP what was downloaded
    say("  -- 1: cancel and keep the download")
    w1 = Watch()
    A.post("/api/job", dict(body, name="setup"))
    s = wait_download(w1, 300_000_000, 600)
    p = (s or {}).get("progress") or {}
    if check(bool(s) and (p.get("bytes") or 0) >= 300_000_000, "download starts and reports progress", "%d MB after %ds" % ((p.get("bytes") or 0) // 1048576, time.time() - T0), "no download progress within 10 minutes: %s" % job_summary(s)):
        kept = p.get("bytes")
        r = A.post("/api/cancel", {"keep": "keep"})
        check(r.get("ok"), "cancel accepted", "", str(r))
        s = wait_job("auto", 120, series=w1)
        time.sleep(3)
        st = status()
        check(st.get("vm") in ("none", "exited", "", "stopped"), "Windows software stopped after cancel", "", "vm=%s" % st.get("vm"))
        check(not helpers(), "no helper programs left after cancel", "", "; ".join(h[:80] for h in helpers()))
        files = storage_state()
        check(any(f.startswith("tmp/") for f in files), "downloaded files are kept after 'keep'", "", "storage now holds: %s" % ", ".join(files)[:200])
        check(st.get("installed") == "0", "Windows is not marked installed", "", "installed=%s" % st.get("installed"))
        w1.analyse("first download")
        # 2. start again: does the download carry on?
        say("  -- 2: start again and see whether the download resumes")
        w2 = Watch()
        A.post("/api/job", dict(body, name="setup"))
        s = wait_download(w2, 1, 240)
        first = ((s or {}).get("progress") or {}).get("bytes")
        if first is not None and kept:
            note("resume check: first reading %d MB (before the cancel it had %d MB). %s" % (first // 1048576, kept // 1048576, "It RESUMED." if first >= kept * 0.8 else "It started again from the beginning."))
        else:
            note("resume check: no reading in the first 4 minutes")
        # 3. cancel again and DELETE
        say("  -- 3: cancel and delete the download")
        time.sleep(15)
        r = A.post("/api/cancel", {"keep": "delete"})
        check(r.get("ok"), "cancel (delete) accepted", "", str(r))
        wait_job("auto", 120)
        time.sleep(3)
        left = storage_state()
        check(not left, "'delete everything' removes the download too", "", "still there: %s" % ", ".join(left)[:200])
        check(not helpers(), "no helper programs left after delete", "", "; ".join(h[:80] for h in helpers()))
    # 4. the real setup, start to finish
    say("  -- 4: the real setup, start to finish (this takes a while)")
    w3 = Watch()
    t = time.time()
    A.post("/api/job", dict(body, name="setup"))
    s = wait_job("auto", 3 * 3600, poll=2.0, series=w3)
    el = time.time() - t
    j = (s or {}).get("job") or {}
    check(j.get("rc") == 0 and not j.get("running"), "Windows is set up", "%d minutes" % (el // 60), "setup did not finish: " + job_summary(s))
    w3.analyse("download in the real run")
    st = status()
    check(st.get("installed") == "1", "Windows is marked installed", "", "installed=%s" % st.get("installed"))
    stages = {}
    for r in w3.rows:
        stages.setdefault(r[1] or "-", [r[0], r[0]])[1] = r[0]
    note("time in each step: " + "; ".join("%s %ds" % (k, v[1] - v[0]) for k, v in stages.items()))
    # leave it in a known state, then check a normal start and stop
    run_job("stop", timeout=240)
    lifecycle(1)


# ----------------------------------------------------------------------- usb ----
def ask(msg):
    say("  >> " + msg)


def usb():
    head("USB: controller session (needs a controller, a USB data cable and your Deck password)")
    if status().get("installed") != "1":
        warn("usb skipped", "Windows is not set up yet")
        return
    if not A.root and not A.start():
        return
    if status().get("vm") == "running":
        run_job("stop", timeout=240)
    ask("Plug in an Xbox controller with a USB DATA cable. Waiting up to 2 minutes...")
    dev = None
    t = time.time()
    while time.time() - t < 120 and not dev:
        try:
            ms = [d for d in A.get("/api/devices")["devices"] if d.get("ms")]
        except Exception:
            ms = []
        dev = ms[0] if ms else None
        time.sleep(2)
    if not check(bool(dev), "controller found", "%s %s" % (dev["id"], dev["name"]) if dev else "", "no Microsoft controller seen"):
        return
    ask("A small window will ask for your Deck password. Type it there (DeckVM never sees it).")
    t = time.time()
    s, el = run_job("xbox", {"ports": [dev["port"]]}, timeout=300)
    j = (s or {}).get("job") or {}
    check(j.get("rc") == 0, "controller session starts", "%.0fs (includes you typing the password)" % el, job_summary(s))
    time.sleep(5)
    st = status()
    check(st.get("usb_session") == "1", "session recorded", "", "usb_session=%s" % st.get("usb_session"))
    check(st.get("driver_block") == "1", "SteamOS Xbox drivers are paused for the session", "", "driver_block=%s" % st.get("driver_block"))
    check(bool(helpers()), "USB helper is running", "", "none found")
    t = time.time()
    while time.time() - t < 90 and "usbfs" not in status().get("usb_owner", ""):
        time.sleep(3)
    check("usbfs" in status().get("usb_owner", ""), "Windows has the controller", "after %ds" % (time.time() - t), "owner=%s" % status().get("usb_owner"))
    s, el = run_job("reattach", timeout=120)
    check(((s or {}).get("job") or {}).get("rc") == 0, "Reconnect button works", "%.0fs" % el, job_summary(s))
    ask("In the Windows screen, open the Start menu and SHUT DOWN Windows (do not use Stop in DeckVM). Waiting up to 3 minutes...")
    t = time.time()
    while time.time() - t < 180 and status().get("vm") == "running":
        time.sleep(3)
    gone = status().get("vm") != "running"
    check(gone, "Windows shut down", "after %ds" % (time.time() - t), "still running after 3 minutes")
    time.sleep(30)
    st = status()
    check(st.get("driver_block") == "0", "controller drivers came back by themselves", "", "driver_block=%s: SteamOS still has them off" % st.get("driver_block"))
    check(not helpers(), "USB helpers have finished", "", "; ".join(h[:80] for h in helpers()))
    t = time.time()
    s, el = run_job("stop", timeout=120)
    check(((s or {}).get("job") or {}).get("rc") == 0 and el < 40, "Stop afterwards needs no password and is quick", "%.0fs" % el, "took %.0fs: %s" % (el, job_summary(s)))
    check(status().get("engine", "") != "root", "state is clean afterwards")


# ---------------------------------------------------------------------- main ----
def main():
    open(OUT, "w").write("")
    say("NerdZap DeckVM self-test  %s" % time.strftime("%Y-%m-%d %H:%M:%S"))
    say("levels: %s   script: %s" % (", ".join(LEVELS), SELF))
    rc, ver = sh(["bash", SELF, "status-kv"], 40)
    say("version: %s" % kv(ver).get("version", "?"))
    order = ["quick", "lifecycle", "full", "usb"]
    wanted = [l for l in order if l in LEVELS or (l == "quick")]
    if "all" in LEVELS:
        wanted = ["quick", "lifecycle", "usb"]
    try:
        for lv in wanted:
            {"quick": quick, "lifecycle": lifecycle, "full": full, "usb": usb}[lv]()
    except KeyboardInterrupt:
        warn("stopped by you (Ctrl+C)")
    except Exception as e:
        import traceback
        bad("the self-test itself hit an error", traceback.format_exc()[-400:])
    finally:
        pass
    fails = [r for r in RES if r[0] == "FAIL"]
    warns = [r for r in RES if r[0] == "WARN"]
    say("")
    say("=== SUMMARY: %d passed, %d warnings, %d FAILED, %d minutes ===" % (len([r for r in RES if r[0] == "PASS"]), len(warns), len(fails), (time.time() - T0) // 60))
    for r in fails:
        say("  FAIL: %s - %s" % (r[1], r[2]))
    for r in warns:
        say("  warn: %s - %s" % (r[1], r[2]))
    if fails:
        say("")
        say("Evidence (last lines of each log):")
        for name in ("gui.log", "session.log", "commands.log", "container.log", "watchdog.log"):
            p = os.path.join(BASE, "logs", name)
            if os.path.exists(p):
                say("--- %s" % name)
                say("\n".join(open(p, errors="replace").read().splitlines()[-25:]))
    say("")
    say("Report file: %s" % OUT)
    if os.path.exists(SERIES) and len(open(SERIES).read().splitlines()) > 1:
        say("Progress readings: %s" % SERIES)
    sys.exit(1 if fails else 0)


main()
SELFTEST_EOF
  command -v python3 >/dev/null || die "Python 3 is needed for the self-test."
  DECKVM_BASE="$BASE" exec python3 -I "$BASE/selftest.py" "$BASE" "$SELF" "$@"
}

write_app_entry() { # the window is class "DeckVM"; without a launcher entry that matches it, the taskbar guesses an icon (it once showed a "W")
  write_icon
  mkdir -p "$(dirname "$APP_FILE")" 2>/dev/null || return 0
  cat > "$APP_FILE" <<ENTRY_EOF
[Desktop Entry]
Type=Application
Name=DeckVM
Comment=Run Windows on your Steam Deck
Exec=bash "$SELF" gui
Icon=$ICON_FILE
StartupWMClass=DeckVM
StartupNotify=false
Terminal=false
Categories=Utility;
ENTRY_EOF
}

cmd_gui() { # start (or reuse) the local GUI server and open its window
  local fresh=0   # 1 when this run starts a new window server, so any window left from the old one is stale
  persist_self
  mkdir -p "$LOGS"
  write_gui_py
  write_askpass
  # a desktop shortcut made by an older version gets the DeckVM icon too
  if [[ -f "$DESKTOP_FILE" ]] && grep -q '^Icon=computer' "$DESKTOP_FILE" 2>/dev/null; then
    sed -i -e "s|^Icon=computer|Icon=$ICON_FILE|" -e '/^Icon=/a StartupWMClass=DeckVM' "$DESKTOP_FILE" 2>/dev/null || true
  fi
  write_app_entry
  if gui_alive; then
    # a window server left over from an older version of this script is replaced
    local want have pid
    want="$(sha1sum "$GUI_PY" | cut -c1-12)"
    have="$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1])).get("ver",""))' "$GUI_INFO" 2>/dev/null)"
    if [[ "$want" != "$have" && -s "$BASE/gui.busy" ]]; then
      # A job is running in the old window server and would be lost with it. Keep it; the newer one starts once it is idle.
      local jn what; jn="$(cat "$BASE/gui.busy" 2>/dev/null)"
      case "$jn" in
        auto) what="setting up Windows";; start) what="starting Windows";; stop|repair) what="stopping Windows";;
        xbox) what="starting the controller update";; usb) what="starting Windows with your USB device";;
        reattach) what="reconnecting the device";; reset) what="deleting Windows";; uninstall) what="removing DeckVM";;
        eject) what="ejecting the install disc";; settings) what="saving settings";; report) what="making a report";;
        *) what="a job";;
      esac
      say "  DeckVM is busy $what, so it is carrying on with the version that is already open. Your Windows is not affected."
      say "  To switch to the newer version, wait for it to finish (or cancel it in DeckVM), then open DeckVM again."
      event "GUI_KEPT_BUSY" "job=$(cat "$BASE/gui.busy" 2>/dev/null)"
    elif [[ "$want" != "$have" ]]; then
      pid="$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))["pid"])' "$GUI_INFO" 2>/dev/null)"
      [[ -n "$pid" ]] && kill "$pid" 2>/dev/null
      sleep 1; rm -f "$GUI_INFO"
      fresh=1
    fi
  fi
  if ! gui_alive; then
    fresh=1
    rm -f "$GUI_INFO"
    # the waiting subshell must not keep the terminal's output open, or "curl | bash" would never return
    ( cd "$BASE" && DECKVM_BASE="$BASE" setsid nohup python3 -I "$GUI_PY" >> "$LOGS/gui.log" 2>&1 < /dev/null ) > /dev/null 2>&1 < /dev/null &
    local i
    for i in $(seq 1 50); do [[ -f "$GUI_INFO" ]] && gui_alive && break; sleep 0.2; done
    gui_alive || die "The DeckVM window could not start. Details: $LOGS/gui.log"
  fi
  local url; url="$(gui_url)"
  [[ -n "$url" ]] || die "The DeckVM window could not start (no address)."
  if [[ $fresh == 1 ]]; then
    # a window from the previous server can only say "restarted"; close it so the new one replaces it
    pkill -f -- '--class=DeckVM' 2>/dev/null && sleep 1
  elif gui_window_open; then
    # one window is enough: a second one would join the first browser process and lose its name and icon
    raise_gui_window
    ok "DeckVM is already open. It has been brought to the front."
    return 0
  fi
  open_gui_window "$url" || { say "  Open this address in your browser: $url"; return 0; }
  ok "DeckVM is open in its own window."
}

cmd_resume() { # a Windows setup is still running in its container but nothing was watching it: see it through
  stage_begin "resume"
  step "Carrying on with the Windows setup"
  load_conf 2>/dev/null || true; load_state
  if installed; then ok "Windows is already set up."; set_stage "ready"; stage_end 0; return 0; fi
  local e found=""
  for e in user root; do [[ "$(engine_vm_state "$e")" == running ]] && { found="$e"; break; }; done
  [[ -n "$found" ]] || die "No Windows setup is running."
  ENGINE="$found"; set_pmv; set_active
  mkdir -p "$LOGS"
  info "Found Windows still installing. Watching it from here."
  # the helpers of the setup that was lost may still be running; start the ones that are not
  pgrep -f "logs -f $NAME" >/dev/null 2>&1 || bg_start container "${PMV[@]}" logs -f "$NAME"
  pgrep -f "who=NerdZapDeckVM" >/dev/null 2>&1 || bg_start inhibit systemd-inhibit --what=sleep:idle --mode=block --who=NerdZapDeckVM --why="Windows VM running" bash -c "$SLEEP_HOLD"
  set_stage "install"
  event "INSTALL_RESUMED" "edition=${WIN_VERSION:-?}"
  wait_for_windows_install
  step "Finishing up"
  save_state INSTALLED 1; INSTALLED=1
  event "INSTALL_DONE" "edition=${WIN_VERSION:-?} (left running, resumed)"
  set_stage "ready"
  ok "Windows is installed and running."
  stage_end 0
}

# -------------------------------------------------------------------- auto ----
A_WIN=""; A_RAM=""; A_DISK=""; A_CORES=""; A_GPU=""; A_JOB=""; A_DESKTOP=0; A_STEAM=0; A_RESEARCH=0; A_XBOXAPP=0; A_SHORTCUTS_ONLY=0; A_ACTION=""; A_CLI=0; GUI_ARGS=()

cmd_reset_windows() {
  confirm "  Really delete your Windows? This cannot be undone." n || { say "  Cancelled."; return 0; }
  graceful_stop_vm; bg_stop_all
  rm_tree "$STORAGE"; clear_active; save_state INSTALLED 0
  # the next Windows gets a fresh login (user and password) from DEFAULT_WIN instead of the old one
  [[ -f "$CONF" ]] && { grep -v -e '^WIN_USER=' -e '^WIN_PASS=' "$CONF" > "$CONF.tmp" 2>/dev/null; mv "$CONF.tmp" "$CONF"; chmod 600 "$CONF" 2>/dev/null; }
  ok "Windows deleted. The VM software is kept."
}

cmd_auto() { # the one-line mode: everything chosen on the website arrives as flags
  [[ "$GUI" == 1 ]] && rm -f "$STAGEFILE"
  stage_begin "auto"
  step "NerdZap DeckVM $TOOL_VERSION"
  persist_self
  if [[ $A_SHORTCUTS_ONLY == 1 ]]; then
    [[ $A_DESKTOP == 1 ]] && cmd_shortcut
    [[ $A_STEAM == 1 ]] && steam_shortcut
    return 0
  fi
  # validate what the website gave us
  if [[ -n "$A_WIN" ]]; then edition_field "$A_WIN" 2 >/dev/null || die "Unknown Windows version '$A_WIN'."; fi
  [[ -z "$A_RAM"   || ( "$A_RAM"   =~ ^[0-9]+$ && "$A_RAM"   -ge 3  && "$A_RAM"   -le 10  ) ]] || die "--ram must be 3 to 10."
  [[ -z "$A_DISK"  || ( "$A_DISK"  =~ ^[0-9]+$ && "$A_DISK"  -ge 30 && "$A_DISK"  -le 256 ) ]] || die "--disk must be 30 to 256."
  [[ -z "$A_CORES" || ( "$A_CORES" =~ ^[0-9]+$ && "$A_CORES" -ge 1  && "$A_CORES" -le 8   ) ]] || die "--cores must be 1 to 8."

  if [[ "$GUI" != 1 && $A_CLI == 0 ]] && gui_possible; then
    # Hand over to the DeckVM window: it does the same work with progress, and no terminal is needed.
    [[ $A_DESKTOP == 1 ]] && cmd_shortcut
    [[ $A_STEAM == 1 ]] && { steam_shortcut || true; }
    if [[ ${#GUI_ARGS[@]} -gt 0 ]]; then printf '%s\n' "${GUI_ARGS[@]}" > "$GUI_PENDING"; else rm -f "$GUI_PENDING"; fi
    cmd_gui
    say "  You can close this terminal window. DeckVM carries on in its own window."
    stage_end 0
    return 0
  fi
  step "Checking your Deck"
  preflight || die "Your Deck is not ready. Fix the red items above and run the command again."
  load_conf 2>/dev/null || true; load_state
  [[ -n "$A_RAM" ]]   && RAM="${A_RAM}G"
  [[ -n "$A_CORES" ]] && CORES="$A_CORES"
  if [[ $A_RESEARCH == 1 ]]; then RESEARCH=1; save_conf RESEARCH 1; fi
  XBOXAPP="$A_XBOXAPP"; save_conf XBOXAPP "$XBOXAPP"
  if installed && [[ -n "$A_WIN" && "$A_WIN" != "$WIN_VERSION" ]]; then
    # A different Windows was asked for than the one already installed. Never quietly keep the old one.
    fail "Windows is already set up here: $(edition_name "$WIN_VERSION"). You asked for $(edition_name "$A_WIN")."
    say
    say "  DeckVM is designed to run a single Windows at the moment, so it cannot set up a second one."
    say
    say "  What would you like to do?"
    say "    1) Start my current Windows ($(edition_name "$WIN_VERSION"))"
    say "    2) Delete it and set up $(edition_name "$A_WIN") instead (everything inside the current Windows is lost)"
    say "    Enter) Do nothing"
    ask "  Choose" ""
    case "$REPLY" in
      1) A_WIN="$WIN_VERSION"; A_JOB=start;;
      2) if confirm "  This deletes your current Windows and everything in it. Really continue?" n; then
           graceful_stop_vm; bg_stop_all
           rm_tree "$STORAGE"; clear_active; save_state INSTALLED 0; INSTALLED=0
           ok "The old Windows was deleted."
         else
           say "  Nothing was changed."; stage_end 1; return 1
         fi;;
      *) say "  Nothing was changed. To switch later, delete the current Windows first (the command under 'Changed your mind?' on the DeckVM page), then run your command again."
         stage_end 1; return 1;;
    esac
  fi
  if installed; then
    ok "Windows is already set up here ($(edition_name "$WIN_VERSION")). Reusing it."
    save_conf RAM "$RAM"; save_conf CORES "$CORES"
    prepare_dirs
  else
    [[ -n "$A_WIN" ]]  && WIN_VERSION="$A_WIN"
    [[ -n "$A_DISK" ]] && DISK="${A_DISK}G"
    step "Setting up Windows (this takes a while)"
    say "  Windows is downloaded and installed by itself. The Deck must stay awake and plugged in."
    setup_core
  fi
  [[ $A_DESKTOP == 1 ]] && cmd_shortcut
  case "$A_JOB" in
    xbox)  cmd_xbox;;
    start) cmd_start;;
  esac
  if [[ $A_STEAM == 1 ]]; then steam_shortcut || true; fi
  stage_end 0
}

# -------------------------------------------------------------------- main ----
main() {
  SELF=""
  [[ -n "${BASH_SOURCE[0]:-}" && -f "${BASH_SOURCE[0]}" ]] && SELF="$(readlink -f "${BASH_SOURCE[0]}")"
  local cmd="${1:-menu}" mode=cmd
  if [[ "$cmd" == --* && "$cmd" != --help ]]; then
    mode=auto; cmd=auto
    while [[ $# -gt 0 ]]; do
      case "$1" in --win|--ram|--disk|--cores|--src) [[ $# -ge 2 ]] || { echo "Missing a value after $1. Run: bash deckvm.sh --help"; exit 1; };; esac
      case "$1" in
        --win)   A_WIN="${2:-}"; GUI_ARGS+=(--win "${2:-}"); shift 2;;
        --ram)   A_RAM="${2:-}"; GUI_ARGS+=(--ram "${2:-}"); shift 2;;
        --disk)  A_DISK="${2:-}"; GUI_ARGS+=(--disk "${2:-}"); shift 2;;
        --cores) A_CORES="${2:-}"; GUI_ARGS+=(--cores "${2:-}"); shift 2;;
        --gpu)   A_GPU=1; GUI_ARGS+=(--gpu); shift;;
        --no-gpu) A_GPU=0; GUI_ARGS+=(--no-gpu); shift;;
        --xbox)  A_JOB=xbox; GUI_ARGS+=(--xbox); shift;;
        --start) A_JOB=start; GUI_ARGS+=(--start); shift;;
        --cli)   A_CLI=1; shift;;
        --desktop-shortcut) A_DESKTOP=1; shift;;
        --steam-shortcut)   A_STEAM=1; shift;;
        --shortcuts-only)   A_SHORTCUTS_ONLY=1; shift;;
        --research|--record-usb) A_RESEARCH=1; GUI_ARGS+=(--record-usb); shift;;
        --xbox-app) A_XBOXAPP=1; GUI_ARGS+=(--xbox-app); shift;;
        --src)   SRC_URL="${2:-}"; shift 2;;
        --reset-windows) A_ACTION=reset; shift;;
        --remove-all)    A_ACTION=remove; shift;;
        *) echo "Unknown option: $1"; echo "Run: bash deckvm.sh --help"; exit 1;;
      esac
    done
  else
    shift || true
  fi
  case "$cmd" in
    _watch_usb|_watch_kernel|_watchdog|_redir) ;;
    *) [[ $EUID -eq 0 ]] && { echo "Do not run this with sudo. It asks for your password when needed."; exit 1; } ;;
  esac
  mkdir -p "$LOGS"
  case "$cmd" in
    _watch_*|_watchdog|_redir|status-kv|devices-kv) ;;
    *)
      exec > >(tee -a "$LOGS/session.log") 2>&1
      echo "===== $(ts) :: deckvm $cmd $* (v$TOOL_VERSION) =====" >> "$LOGS/session.log"
      trap 'sleep 0.3' EXIT
      ;;
  esac
  load_conf 2>/dev/null || true
  WIN_VERSION="${WIN_VERSION:-11}"; WIN_USER="${WIN_USER:-nerdzap}"; WIN_PASS="${WIN_PASS:-}"
  RAM="${RAM:-6G}"; CORES="${CORES:-4}"; DISK="${DISK:-40G}"; RESEARCH="${RESEARCH:-0}"; XBOXAPP="${XBOXAPP:-0}"
  [[ "${DECKVM_RESEARCH:-}" == 1 || "${DECKVM_RECORD_USB:-}" == 1 ]] && RESEARCH=1
  CPID=0
  load_state
  BASE_ENGINE=user; [[ "${ROOTLESS:-1}" == 0 ]] && BASE_ENGINE=root
  ENGINE="$BASE_ENGINE"; [[ $EUID -eq 0 ]] && ENGINE=root

  if [[ $mode == auto && -n "$A_ACTION" ]]; then
    case "$A_ACTION" in
      reset)  cmd_reset_windows;;
      remove) cmd_uninstall;;
    esac
    return 0
  fi

  case "$cmd" in
    auto)     cmd_auto;;
    resume)   cmd_resume;;
    menu)     cmd_menu;;
    setup)    cmd_setup;;
    start)    cmd_start;;
    xbox)     cmd_xbox;;
    usb)      cmd_usb;;
    stop)     cmd_stop;;
    status)   cmd_status;;
    settings) cmd_settings;;
    cleanup)  cmd_cleanup;;
    report)   cmd_report;;
    note)     cmd_note "$@";;
    logs)     cmd_logs;;
    shortcut) cmd_shortcut;;
    steam)    steam_shortcut;;
    gui)      cmd_gui;;
    selftest) cmd_selftest "$@";;
    status-kv)  cmd_status_kv;;
    devices-kv) cmd_devices_kv;;
    set)      cmd_set "$@";;
    reattach) cmd_reattach;;
    _watch_usb)    cmd__watch_usb;;
    _watch_kernel) cmd__watch_kernel;;
    _watchdog)     cmd__watchdog "$@";;
    _redir)        cmd__redir "$@";;
    _cancelclean)  cmd__cancelclean "$@";;
    eject)         cmd_eject;;
    open-shared)   cmd_open_shared;;
    help|-h|--help) cmd_help;;
    *) echo "Unknown command: $cmd"; cmd_help; exit 1;;
  esac
}

[[ "${DECKVM_SOURCE_ONLY:-}" == 1 ]] || main "$@"
