#!/bin/bash
# Builds, runs and tests the Windows app (apps/p3-windows) in a Windows 11 VM on this Mac, QEMU or Parallels, over SSH.
# You edit on the Mac; the app builds and runs in Windows (WinUI 3 builds only there).
#
# Target: $PI_WIN_TARGET (qemu or parallels), else the one that is running.
#   tools/vm setup [--native-aot]  once per VM: SSH key, OpenSSH in Windows (automatic on Parallels), tools in C:\Tools;
#                               --native-aot adds the MSVC Build Tools that `publish` needs
#   tools/vm status             target, address, user, tools, desktop session, app
#   tools/vm sync               copy the sources into the VM (C:\dev\p3-windows)
#   tools/vm test               sync, then the unit tests (Pi.Core.Tests)
#   tools/vm format [--check]   sync, `dotnet format` in the VM (whitespace, code style and analyzer fixes), the C#
#                               files it changed copied back here; --check only says whether something would change
#                               (exit 2 then)
#   tools/vm build              sync, stop the app, build it (Debug, for the VM's architecture)
#   tools/vm ui-test [filter]   build, then the UI tests (Pi.UITests) in the desktop session; they take the screen
#   tools/vm run                start the app in the desktop session, with WebView2's DevTools on 9222
#   tools/vm dev                build + run
#   tools/vm stop               stop the app (the Debug build)
#   tools/vm publish [rid]      Release, Native AOT, to C:\dev\p3-windows-publish\<rid> (setup --native-aot)
#   tools/vm measure [rid] [n]  publish, then size, and on the stand-in's page and on a blank page (tools/blank.html)
#                               time to the page shown and settled memory of the published app (n launches after a
#                               first, default 5; tools/measure.ps1); it takes the screen for some minutes
#   tools/vm shot [file.png]    screenshot of the VM's screen, default /tmp/win11.png
#   tools/vm page-shot [file]   screenshot of the page only (CDP), default /tmp/win11-page.png
#   tools/vm eval '<js>'        evaluate JavaScript in the page (CDP through an SSH tunnel), print the JSON result
#   tools/vm input <cmd> ...    real Windows input in the desktop session (tools/input.ps1): hittest, click, drag, key
#   tools/vm trace [seconds]    CPU trace of the running Debug build's Pi (dotnet-trace), copied to /tmp (path printed)
#   tools/vm ps '<command>'     run a PowerShell command in the VM (session 0: no desktop)
#   tools/vm ssh                interactive shell in the VM
#
# The VM's checkout and published app are shared by every session on this Mac: a command that syncs, stops or traces the
# Debug build's Pi holds a lock from then to its end, a publish and a measure from before their sync to their last
# write, and `ui-test` hands it to its tests, which hold it until they end, also when the command was cut off; one that
# finds it held by another refuses (the error names the lock's file, to remove by hand when its holder was killed
# outright).
#
# Settings: PI_WIN_TARGET; PI_WIN_STATE (SSH key and known hosts, default ~/.config/pi-windows);
# PI_WIN_QEMU_DIR (default ~/Developer/VMs/win11), PI_WIN_QEMU_USER (default: your user name on the Mac);
# PI_WIN_PARALLELS_VM (default: the running Parallels VM).
#
# The VMs: a Windows 11 VM signed in to its desktop. Under QEMU (aarch64) it is started from $PI_WIN_QEMU_DIR with the
# name `win11`, its monitor on `monitor.sock` in that folder and its SSH port forwarded to 127.0.0.1:2222 (the
# `run.sh` of ~/Developer/VMs/win11 does all three); under Parallels, Parallels Tools installed. On the Mac: ssh, tar,
# node (the DevTools client), python3 and nc. Run `tools/vm setup` once per VM before anything else.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
APP=$(cd "$HERE/.." && pwd)
STATE=${PI_WIN_STATE:-$HOME/.config/pi-windows}
KEY=$STATE/id_ed25519
QEMU_DIR=${PI_WIN_QEMU_DIR:-$HOME/Developer/VMs/win11}
REMOTE='C:\dev\p3-windows'
PUBLISH='C:\dev\p3-windows-publish'
DEVTOOLS_PORT=9222

# ——— Targets: where the VM is, how to reach it, how to see its screen ———

qemu_running() { [ -S "$QEMU_DIR/monitor.sock" ] && pgrep -qf "qemu-system-aarch64 -name win11"; }

# The Parallels VM to use: $PI_WIN_PARALLELS_VM, else the first running one.
parallels_vm() {
	command -v prlctl >/dev/null || return 0
	prlctl list -a -f -j | python3 -c '
import json, os, sys
want = os.environ.get("PI_WIN_PARALLELS_VM")
for vm in json.load(sys.stdin):
    if (want and vm["name"] == want) or (not want and vm["status"] == "running"):
        print(vm["name"]); break'
}

resolve_target() {
	if [ -n "${PI_WIN_TARGET:-}" ]; then
		TARGET=$PI_WIN_TARGET
	else
		local found=()
		qemu_running && found+=(qemu)
		[ -n "$(parallels_vm)" ] && found+=(parallels)
		case ${#found[@]} in
			1) TARGET=${found[0]} ;;
			0) echo "No Windows VM is running: start $QEMU_DIR/run.sh or the Parallels VM." >&2; exit 1 ;;
			*) echo "Both QEMU and Parallels are running: set PI_WIN_TARGET=qemu or PI_WIN_TARGET=parallels." >&2; exit 1 ;;
		esac
	fi
	case $TARGET in
		qemu)
			HOST=127.0.0.1 PORT=2222 USER_NAME=${PI_WIN_QEMU_USER:-$USER} ;;
		parallels)
			PRL_VM=$(parallels_vm)
			[ -n "$PRL_VM" ] || { echo "No Parallels VM found (PI_WIN_PARALLELS_VM=${PI_WIN_PARALLELS_VM:-})." >&2; exit 1; }
			HOST=$(prlctl list -a -f -j | python3 -c "import json,sys; print(next(v['ip_configured'] for v in json.load(sys.stdin) if v['name'] == sys.argv[1]))" "$PRL_VM")
			PORT=22
			USER_NAME=$(cat "$STATE/parallels-user" 2>/dev/null || true) ;;
		*) echo "Unknown PI_WIN_TARGET=$TARGET (qemu or parallels)." >&2; exit 1 ;;
	esac
	SSH_OPTS=(-i "$KEY" -o IdentitiesOnly=yes -o UserKnownHostsFile="$STATE/known_hosts" -o StrictHostKeyChecking=accept-new
		-o ConnectTimeout=5 -o ServerAliveInterval=15 -o LogLevel=ERROR)
	SSH=(ssh "${SSH_OPTS[@]}" -p "$PORT" "$USER_NAME@$HOST")
	SCP=(scp "${SSH_OPTS[@]}" -P "$PORT")
}

shot() {
	local file=${1:-/tmp/win11.png}
	rm -f "$file"
	case $TARGET in
		qemu)
			# QEMU's monitor reads a path from its own working directory and splits one with a space: it writes to an
			# absolute path of this run's own, moved into place once it is there (another command may write $file
			# meanwhile); its folder is removed either way (no EXIT trap: a command holding the VM's lock keeps its own).
			local dir
			dir=$(mktemp -d /tmp/pi-vm-shot.XXXXXX)
			printf 'screendump %s -f png\n' "$dir/screen.png" | nc -U "$QEMU_DIR/monitor.sock" -w 1 >/dev/null || true
			for _ in 1 2 3 4 5 6 7 8 9 10; do [ -s "$dir/screen.png" ] && break; sleep 0.3; done
			local moved=false
			[ -s "$dir/screen.png" ] && mv "$dir/screen.png" "$file" && moved=true
			rm -rf "$dir"
			$moved || { echo "shot: QEMU wrote no screenshot, or it could not be moved to $file" >&2; exit 1; } ;;
		parallels)
			prlctl capture "$PRL_VM" --file "$file" >/dev/null ;;
	esac
	[ -s "$file" ] || { echo "shot: no screenshot was written" >&2; exit 1; }
	echo "$file"
}

# ——— One-time setup ———

setup() {
	mkdir -p "$STATE"
	[ -f "$KEY" ] || ssh-keygen -q -t ed25519 -N '' -C "pi-windows $(whoami)@$(hostname -s)" -f "$KEY"
	case $TARGET in
		parallels) setup_parallels_ssh ;;
		qemu) "${SSH[@]}" exit 2>/dev/null || setup_qemu_ssh ;;
	esac
	ps "New-Item -ItemType Directory -Force C:\\Tools | Out-Null"
	"${SCP[@]}" "$HERE"/guest/desktop-run.ps1 "$HERE"/guest/setup-dev.ps1 "$USER_NAME@$HOST:C:/Tools/"
	local aot=""
	[ "${1:-}" = --native-aot ] && aot=" -NativeAot"
	ps "& C:\\Tools\\setup-dev.ps1$aot"
	status
}

# QEMU has no way to run commands in Windows, so the person types one short line in the VM. It fetches the script
# from the Mac: the VM reaches the Mac's loopback at 10.0.2.2.
setup_qemu_ssh() {
	local dir pid port
	dir=$(mktemp -d)
	port=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
	{ echo "\$PublicKey = '$(cat "$KEY.pub")'"; grep -v '^param(' "$HERE/guest/enable-ssh.ps1"; } >"$dir/ssh.ps1"
	python3 -m http.server "$port" --bind 127.0.0.1 --directory "$dir" >/dev/null 2>&1 &
	pid=$!
	disown
	trap "kill $pid 2>/dev/null; rm -rf '$dir'" EXIT
	# Two steps, not iex (iwr ...): Defender blocks that download-and-run pattern (measured over SSH).
	echo "In the VM, open PowerShell as administrator and type:"
	echo
	echo "    iwr http://10.0.2.2:$port/ssh.ps1 -OutFile \$env:TEMP\\ssh.ps1; powershell -ExecutionPolicy Bypass -File \$env:TEMP\\ssh.ps1"
	echo
	echo "Waiting for SSH ($USER_NAME@$HOST:$PORT) ..."
	until "${SSH[@]}" exit 2>/dev/null; do sleep 3; done
	kill "$pid" 2>/dev/null || true
	rm -rf "$dir"
	trap - EXIT
}

# Parallels Tools run commands in Windows without SSH (as SYSTEM), so setup turns SSH on by itself.
setup_parallels_ssh() {
	if ! prlctl exec "$PRL_VM" cmd /c exit 0 >/dev/null 2>&1; then
		echo "Parallels cannot run commands in \"$PRL_VM\" yet: finish Windows setup, sign in, and let Parallels Tools install." >&2
		exit 1
	fi
	local user
	user=$(prlctl exec "$PRL_VM" powershell -NoProfile -Command "(Get-CimInstance Win32_ComputerSystem).UserName" | tr -d '\r' | tail -1)
	[ -n "$user" ] || { echo "Nobody is signed in to Windows in \"$PRL_VM\"; sign in and rerun." >&2; exit 1; }
	# defaultuser0 is the account Windows setup runs as before the real one exists.
	[[ $user != *\\defaultuser0 ]] || { echo "Windows setup is still running in \"$PRL_VM\"; finish it and rerun." >&2; exit 1; }
	USER_NAME=${user##*\\}
	printf '%s\n' "$USER_NAME" >"$STATE/parallels-user"
	SSH=(ssh "${SSH_OPTS[@]}" -p "$PORT" "$USER_NAME@$HOST")
	# prlctl exec drops command lines over about 4 KB, so the script goes through stdin, one statement per line.
	echo "Turning on SSH in \"$PRL_VM\" (installing OpenSSH from Windows Update can take 15 minutes) ..."
	printf '%s\r\n' \
		"[IO.File]::WriteAllBytes('C:\\Windows\\Temp\\enable-ssh.ps1', [Convert]::FromBase64String('$(base64 <"$HERE/guest/enable-ssh.ps1" | tr -d '\n')'))" \
		"powershell -NoProfile -ExecutionPolicy Bypass -File C:\\Windows\\Temp\\enable-ssh.ps1 -PublicKey '$(cat "$KEY.pub")'" |
		prlctl exec "$PRL_VM" powershell -NoProfile -Command -
	"${SSH[@]}" exit
}

status() {
	echo "target: $TARGET${PRL_VM:+ ($PRL_VM)}, $USER_NAME@$HOST:$PORT"
	# query.exe is missing on Windows Home; Win32_ComputerSystem names the user signed in at the console.
	ps "\$u = (Get-CimInstance Win32_ComputerSystem).UserName
'windows: ' + (Get-CimInstance Win32_OperatingSystem).Caption + ' ' + [Environment]::OSVersion.Version + ' ' + \$env:PROCESSOR_ARCHITECTURE
'desktop session: ' + \$(if (\$u) { \$u } else { 'none: sign in to Windows' })
'dotnet: ' + \$(if (Test-Path C:\\Tools\\dotnet\\dotnet.exe) { (& C:\\Tools\\dotnet\\dotnet.exe --version) } else { 'missing: tools/vm setup' })
'desktop-run: ' + (Test-Path C:\\Tools\\desktop-run.ps1)
$ARCH; \$exe = $EXE
'app (Debug build): ' + \$(if (Get-Process Pi -ErrorAction SilentlyContinue | Where-Object { \$_.Path -eq \$exe }) { 'running' } else { 'not running' })"
}

# ——— The loop ———

encode() { printf '%s' "$1" | iconv -f UTF-8 -t UTF-16LE | base64; }

# Runs a PowerShell script in the VM: stdout, stderr and the exit code come back as from a local command.
# A script file run with -File does that; -Command and -EncodedCommand turn Write-Host and errors into CLIXML on stderr.
# So a short -EncodedCommand writes the script to a temporary file and runs it with -File, on the same SSH handles.
ps() {
	local script b64 bootstrap
	script="\$ErrorActionPreference='Stop'; \$ProgressPreference='SilentlyContinue'
[Console]::OutputEncoding = \$OutputEncoding = New-Object Text.UTF8Encoding \$false
$1"
	b64=$(printf '%s' "$script" | base64)
	bootstrap="\$ProgressPreference = 'SilentlyContinue'
\$f = Join-Path \$env:TEMP ('vm-' + [guid]::NewGuid().ToString('n') + '.ps1')
[IO.File]::WriteAllBytes(\$f, [byte[]](0xEF, 0xBB, 0xBF) + [Convert]::FromBase64String('$b64'))
try {
  # Quoted: Start-Process joins the arguments into one command line, and the temporary folder may hold a space.
  \$p = Start-Process powershell.exe -ArgumentList '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', ('\"' + \$f + '\"') -NoNewWindow -PassThru
  \$null = \$p.Handle  # without it, ExitCode stays empty
  \$p.WaitForExit(); \$code = \$p.ExitCode
} finally { Remove-Item \$f }
exit \$code"
	# The SSH shell is PowerShell too (enable-ssh.ps1), which reports a native command's failure only as 1.
	"${SSH[@]}" "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $(encode "$bootstrap"); exit \$LASTEXITCODE"
}

# The app's folder, without build output; what is no longer on the Mac goes in the VM too (the build compiles every file
# it finds), the build output stays.
# Under the lock, held from here to the command's end unless this run holds it already.
sync() {
	hold
	ps "New-Item -ItemType Directory -Force '$REMOTE' | Out-Null
Get-ChildItem '$REMOTE' -Recurse -File | Where-Object { \$_.FullName -notmatch '\\\\(bin|obj|TestResults)\\\\' } | Remove-Item -Force"
	COPYFILE_DISABLE=1 tar -czf - -C "$APP" --exclude bin --exclude obj --exclude .vs --exclude TestResults . |
		"${SSH[@]}" "tar -xzf - -C ${REMOTE//\\//}"
}

# dotnet format in the VM (the .NET SDK is there), then the C# files it changed back here. A file edited here since the
# sync is left as it is and named (several sessions may work in this checkout): checked right before it is replaced.
format() {
	if [ "${1:-}" = "--check" ]; then
		sync
		ps "Set-Location '$REMOTE'; & '$DOTNET' format Pi.slnx --verify-no-changes -v:minimal; exit \$LASTEXITCODE"
		return
	fi
	local before out code back file
	before=$(cd "$APP" && find . -name '*.cs' -not -path '*/bin/*' -not -path '*/obj/*' -exec shasum {} + | sort -k2)
	sync
	# dotnet format's report, then the files whose content it changed, each as `changed: path`.
	out=$(ps "Set-Location '$REMOTE'
\$files = Get-ChildItem -Recurse -Filter *.cs | Where-Object { \$_.FullName -notmatch '\\\\(bin|obj|TestResults)\\\\' }
\$hashes = @{}; foreach (\$f in \$files) { \$hashes[\$f.FullName] = (Get-FileHash \$f.FullName).Hash }
& '$DOTNET' format Pi.slnx -v:minimal; if (\$LASTEXITCODE) { exit \$LASTEXITCODE }
foreach (\$f in \$files) {
	if ((Get-FileHash \$f.FullName).Hash -ne \$hashes[\$f.FullName]) {
		'changed: ' + (Resolve-Path -Relative \$f.FullName).Substring(2).Replace('\\', '/')
	}
}" | tr -d '\r') || { code=$?; printf '%s\n' "$out"; exit "$code"; }
	grep -v '^changed: ' <<<"$out" || true
	grep -q '^changed: ' <<<"$out" || { echo "nothing to format"; return; }
	back=$(mktemp -d)
	"${SSH[@]}" "tar -czf - -C ${REMOTE//\\//} --exclude bin --exclude obj --exclude TestResults ." |
		tar -xzf - -C "$back" --include '*.cs'
	while IFS= read -r file; do
		if [ "$(cd "$APP" && shasum "./$file" 2>/dev/null)" != "$(awk -v f="./$file" '$2 == f' <<<"$before")" ]; then
			echo "left as it is (edited here since the sync): $file" >&2
		else
			mv "$back/$file" "$APP/$file"
			echo "formatted: $file"
		fi
	done < <(sed -n 's/^changed: //p' <<<"$out")
	rm -rf "$back"
}

# The Debug build's Pi only ($EXE): the published app a measure runs, and any other Pi, are left as they are.
stop() {
	# Under the lock: the Debug build's Pi is the app another session's UI tests may be running.
	hold
	ps "$ARCH; \$exe = $EXE
Get-Process Pi -ErrorAction SilentlyContinue | Where-Object { \$_.Path -eq \$exe } | Stop-Process -Force
Start-Sleep -Milliseconds 300"
}

DOTNET='C:\Tools\dotnet\dotnet.exe'

# The VM's architecture as MSBuild and the runtime name it.
ARCH='$platform = if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64") { "ARM64" } else { "x64" }; $rid = "win-" + $platform.ToLower()'

build() {
	sync
	stop
	ps "Set-Location '$REMOTE'; $ARCH
& '$DOTNET' build Pi\\Pi.csproj -c Debug -r \$rid -p:Platform=\$platform -v:minimal -nologo
if (\$LASTEXITCODE) { exit \$LASTEXITCODE }"
}

# The Debug build's Pi.exe for the VM's architecture (after $ARCH), as `build` makes it.
EXE="'$REMOTE\\Pi\\bin\\' + \$platform + '\\Debug\\net10.0-windows10.0.26100.0\\' + \$rid + '\\Pi.exe'"

run() {
	stop
	ps "$ARCH; \$exe = $EXE
if (-not (Test-Path \$exe)) { throw 'not built: tools/vm build' }
C:\\Tools\\desktop-run.ps1 -Exe \$exe -Env 'WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=$DEVTOOLS_PORT'
Start-Sleep 2; Get-Process Pi | Select-Object Id, SessionId | Format-Table -AutoSize | Out-String"
}

# The UI tests launch the app themselves (PI_APP), in the desktop session, where windows and input exist.
# The lock is handed to the tests: from the call that queues them on, this command no longer releases it (its trap is
# disarmed before that call), and the tests release it at their own end (tools/ui-test.ps1). The handoff is taken only
# from this run's own lock; a call cut off on the way leaves the lock held, to remove by hand.
ui_test() {
	build
	ps "Set-Location '$REMOTE'; $ARCH
& '$DOTNET' build Pi.UITests\\Pi.UITests.csproj -c Debug -p:Platform=\$platform -v:minimal -nologo
if (\$LASTEXITCODE) { exit \$LASTEXITCODE }"
	trap - EXIT
	ps "Set-Location '$REMOTE'; $ARCH
if ((Get-Content '$LOCK' -ErrorAction SilentlyContinue) -ne '$LOCK_ID') { Write-Error 'ui-test: the lock is no longer this run''s' }
Set-Content -NoNewline -Path '$LOCK' -Value '$LOCK_ID-tests'
\$exe = $EXE
\$filter = '${1:-}'
\$arguments = 'test Pi.UITests\\Pi.UITests.csproj --no-build -p:Platform=' + \$platform + ' -v:minimal -nologo --logger console;verbosity=normal'
if (\$filter) { \$arguments += ' --filter ' + \$filter }
\$run = '-NoProfile -ExecutionPolicy Bypass -File \"$REMOTE\\tools\\ui-test.ps1\" -DotNet \"$DOTNET\" -Lock \"$LOCK\" -LockId $LOCK_ID-tests -Arguments \"' + \$arguments + '\"'
C:\\Tools\\desktop-run.ps1 -Exe powershell.exe -Arguments \$run -WorkingDirectory '$REMOTE' -Env ('PI_APP=' + \$exe) -Wait -TimeoutSec 900
exit \$LASTEXITCODE"
}

# A CPU trace of the Debug build's Pi (dotnet-trace), under the lock (a build in another session would stop it), written
# under this run's own name and copied only once the collector succeeded: never an earlier run's trace.
trace() {
	local seconds=$1 name copy
	# dotnet-trace takes a zero duration as no stop timer: the lock would be held without end.
	case "$seconds" in '' | *[!0-9]*) echo "trace: seconds must be a whole number" >&2; exit 2 ;; esac
	[ "$seconds" -ge 1 ] || { echo "trace: at least 1 second" >&2; exit 2; }
	hold
	name=$LOCK_ID
	# Of this run on the Mac too: a trace on the other VM target writes its own.
	copy=/tmp/win11-$name.speedscope.json
	# Its files in the VM go also when the collector failed (a partial capture).
	ps "$ARCH; \$exe = $EXE
\$app = @(Get-Process Pi -ErrorAction SilentlyContinue | Where-Object { \$_.Path -eq \$exe })
if (\$app.Count -ne 1) { Write-Error 'trace: the Debug build is not running (tools/vm run)' }
New-Item -ItemType Directory -Force C:\\dev\\diag | Out-Null
& \"\$env:USERPROFILE\\.dotnet\\tools\\dotnet-trace.exe\" collect -p \$app[0].Id --duration ([TimeSpan]::FromSeconds($seconds).ToString('dd\\:hh\\:mm\\:ss')) --format Speedscope -o 'C:\\dev\\diag\\$name.nettrace' | Select-Object -Last 1
if (\$LASTEXITCODE) { \$code = \$LASTEXITCODE; Remove-Item 'C:\\dev\\diag\\$name.*' -ErrorAction SilentlyContinue; exit \$code }"
	if ! "${SCP[@]}" "$USER_NAME@$HOST:C:/dev/diag/$name.speedscope.json" "$copy"; then
		rm -f "$copy"
		ps "Remove-Item 'C:\\dev\\diag\\$name.*' -ErrorAction SilentlyContinue"
		exit 1
	fi
	ps "Remove-Item 'C:\\dev\\diag\\$name.*' -ErrorAction SilentlyContinue"
	echo "$copy (open in https://www.speedscope.app)"
}

# The runtimes the app is built for: anything else is refused before anything happens (a runtime is part of a path).
check_rid() {
	case ${1:-} in
		""|win-x64|win-arm64) ;;
		*) echo "unknown runtime: $1 (win-x64 or win-arm64)" >&2; exit 2 ;;
	esac
}

# The VM's checkout and published app, held by one run at a time (its id inside, LOCK_ID while this run holds it): a
# command that syncs, stops or traces the Debug build's Pi (run, stop and trace too), a publish or a measure.
LOCK="$PUBLISH.lock"
LOCK_ID=''

# Takes the lock for this run, a $1 (the command), and releases it when bash exits; refused while another holds it.
lock() {
	LOCK_ID=$1-$(uuidgen | tr -d - | tr '[:upper:]' '[:lower:]')
	# Released only by its holder (global: the trap reads it when bash exits), and armed before the attempt: a lock
	# taken whose reply SSH lost is released all the same; one refused stays its holder's, and one handed to the UI tests
	# theirs (ui_test).
	UNLOCK="if ((Get-Content '$LOCK' -ErrorAction SilentlyContinue) -eq '$LOCK_ID') { Remove-Item -Force '$LOCK' }"
	trap 'ps "$UNLOCK"' EXIT
	ps "New-Item -ItemType Directory -Force (Split-Path '$LOCK') | Out-Null
try { New-Item -ItemType File -Path '$LOCK' -Value '$LOCK_ID' -ErrorAction Stop | Out-Null } catch {
Write-Error \"\$(Get-Content '$LOCK' -ErrorAction SilentlyContinue) holds the VM's checkout and published app; if it no longer runs, remove $LOCK\" }"
}

# Takes the lock for the command under way unless this run holds it already; held to the command's end.
hold() {
	[ -n "$LOCK_ID" ] || lock "$cmd"
}

# Releases the lock; the trap stays armed until the release came back (one again finds the lock not this run's).
unlock() {
	ps "$UNLOCK"
	trap - EXIT
	LOCK_ID=''
}

# The published app in the folder it replaces is stopped first (its files are in use); a Pi running from anywhere else
# (the Debug build, a developer's) is left as it is. Run while this run holds the lock.
publish() {
	check_rid "${1:-}"
	sync
	ps "Set-Location '$REMOTE'; $ARCH
if ('${1:-}') { \$rid = '${1:-}' }
\$target = if (\$rid -eq 'win-arm64') { 'ARM64' } else { 'x64' }
\$folder = '$PUBLISH\\' + \$rid
Get-Process Pi -ErrorAction SilentlyContinue | Where-Object { \$_.Path -eq (Join-Path \$folder 'Pi.exe') } | Stop-Process -Force
Remove-Item -Recurse -Force \$folder -ErrorAction SilentlyContinue
& '$DOTNET' publish Pi\\Pi.csproj -c Release -r \$rid -p:Platform=\$target -o ('$PUBLISH\\' + \$rid) -v:minimal -nologo
if (\$LASTEXITCODE) { exit \$LASTEXITCODE }"
}

# Size, start and memory of the published app (Release, Native AOT), on the stand-in's page and on a blank page that
# speaks the bridge (tools/blank.html, put in place of the stand-in's page in the published folder for its run only,
# put back also when the run fails: the app's own cost). tools/measure.ps1 launches the app in the desktop session and
# measures it as the macOS app is measured (its header says how). The app runs with a WebView2 data folder of the
# measurement's own (MEASURE_DATA, under the VM user's %LocalAppData%). The cleanup is in place before the first
# launch: an interrupted run asks measure.ps1 to stop, ends only the measured app and puts the page back. The Mac's
# load average goes with each page.
MEASURE_DATA='$env:LOCALAPPDATA\pi-measure\WebView2'

measure() {
	local rid=${1:-} runs=${2:-5} dir exe page
	case "$runs" in '' | *[!0-9]*) echo "measure: runs must be a whole number" >&2; exit 2 ;; esac
	[ "$runs" -ge 1 ] || { echo "measure: at least 1 run after the first launch" >&2; exit 2; }
	check_rid "$rid"
	[ -n "$rid" ] || rid=$(ps "$ARCH; \$rid" | tr -d '\r')
	# Another measure or a publish would stop this one's app, share its data folder and take its page's backup away.
	lock measure
	# This measure's own: its stop marker and its scheduled tasks are told by it.
	MEASURE_ID=$LOCK_ID
	publish "$rid"
	dir="$PUBLISH\\$rid"
	exe="$dir\\Pi.exe"
	page="$dir\\StandIn\\index.html"
	echo "== size: $dir"
	ps "& '$REMOTE\\tools\\measure.ps1' size '$dir'"
	# Asks a run under way to stop, ends the measured app, puts the stand-in's page back. Global, not local: the trap
	# reads it when bash exits.
	cleanup="New-Item -Force -ItemType File \"$MEASURE_DATA.$MEASURE_ID.stop\" | Out-Null; Start-Sleep 5
try { & '$REMOTE\\tools\\measure.ps1' stop '$exe' \"$MEASURE_DATA\" } finally {
if (Test-Path '$page.measured') { Move-Item -Force '$page.measured' '$page' }
# This measure's scheduled task, left registered when the SSH command that waited for it was cut off: told by the id
# in its command (encoded in its arguments), never another session's; one still running is given 30 s to see the stop
# and end first.
\$ours = { @(Get-ScheduledTask -TaskName 'desktop-run-*' | Where-Object {
[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((\$_.Actions[0].Arguments -split ' ')[-1])) -match '$MEASURE_ID' }) }
\$deadline = (Get-Date).AddSeconds(30)
while (@(& \$ours | Where-Object State -eq 'Running').Count -gt 0 -and (Get-Date) -lt \$deadline) { Start-Sleep 1 }
if (@(& \$ours | Where-Object State -eq 'Running').Count -gt 0) {
# Still running: its marker stays for it to see, and the lock stays its.
Write-Warning 'measure: its task still runs after 30 s; its stop marker and the lock stay, the task stays registered'
} else {
& \$ours | Unregister-ScheduledTask -Confirm:\$false
# Last: no task of this measure is left to start and miss it (the markers piled up).
Remove-Item -Force \"$MEASURE_DATA.$MEASURE_ID.stop\" -ErrorAction SilentlyContinue
$UNLOCK } }"
	trap 'ps "$cleanup"' EXIT
	measure_page "$exe" "the stand-in's page" "$runs"
	ps "Copy-Item -Force '$page' '$page.measured'; Copy-Item -Force '$REMOTE\\tools\\blank.html' '$page'"
	measure_page "$exe" "a blank page" "$runs"
	# Put back while the lock is held and the cleanup armed; then only the release is left to do.
	ps "if (Test-Path '$page.measured') { Move-Item -Force '$page.measured' '$page' }"
	trap 'ps "$UNLOCK"' EXIT
	unlock
}

measure_page() {
	local exe=$1 page=$2 runs=$3
	echo "== $page (Mac load average: $(sysctl -n vm.loadavg))"
	ps "C:\\Tools\\desktop-run.ps1 -Exe powershell.exe -Wait -TimeoutSec 3600 -Arguments ('-NoProfile -ExecutionPolicy Bypass -File $REMOTE\\tools\\measure.ps1 run \"$exe\" \"' + \"$MEASURE_DATA\" + '\" $runs $MEASURE_ID')
exit \$LASTEXITCODE" | tr -d '\r'
	echo "(Mac load average after: $(sysctl -n vm.loadavg))"
}

# DevTools listens on the VM's loopback; an SSH forward reaches it, on a Mac port of each target's own (DEVTOOLS_MAC),
# so a command for one VM never reaches the other's page and never cuts the other's tunnel.
tunnel() {
	case $TARGET in qemu) DEVTOOLS_MAC=9222 ;; parallels) DEVTOOLS_MAC=9223 ;; esac
	# The forward, written once: this script's tunnel is told by it (tunnel_up and the cleanup below).
	DEVTOOLS_FORWARD="127.0.0.1:$DEVTOOLS_MAC:127.0.0.1:$DEVTOOLS_PORT"
	local pid
	tunnel_up && return
	# Only this script's tunnels on this target's port (its key, read literally, and one of its two forwards: the
	# current one, or the earlier `-L <port>:…`, which also binds the port) that are not the current one to the VM's
	# current address, which may be another command's, being made. Any other tunnel there is refused, never stopped.
	local line stale=()
	for pid in $(pgrep -f "ssh .*-L (127\.0\.0\.1:)?$DEVTOOLS_MAC:" || true); do
		line=$(command ps -o command= -p "$pid") || continue
		grep -qF -- "ssh -i $KEY " <<<"$line" || continue
		grep -qF -- "-L $DEVTOOLS_FORWARD" <<<"$line" || grep -qF -- "-L $DEVTOOLS_MAC:127.0.0.1:$DEVTOOLS_PORT" <<<"$line" ||
			continue
		grep -qF -- "-p $PORT $USER_NAME@$HOST " <<<"$line" && grep -qF -- "-L $DEVTOOLS_FORWARD" <<<"$line" && continue
		kill "$pid" 2>/dev/null && stale+=("$pid")
	done
	# The port free before the bind: a stopped tunnel's end is waited for.
	for pid in ${stale[@]+"${stale[@]}"}; do
		for _ in $(seq 20); do
			kill -0 "$pid" 2>/dev/null || break
			sleep 0.25
		done
	done
	# On the Mac's IPv4 loopback, where cdp.mjs connects. Another command may bind it first: its tunnel serves this one
	# too, once it listens; anything else on the port is refused rather than talked to.
	"${SSH[@]}" -f -N -o ExitOnForwardFailure=yes -L "$DEVTOOLS_FORWARD" && return
	for _ in $(seq 20); do
		tunnel_up && return
		sleep 0.25
	done
	echo "tunnel: no tunnel to the VM on 127.0.0.1:$DEVTOOLS_MAC (ssh's error above; another program may hold the port)" >&2
	exit 1
}

# Whether this script's SSH tunnel (its key) to the VM's current address, forwarding to the VM's DevTools port, listens
# on the Mac's 127.0.0.1:$DEVTOOLS_MAC: another tunnel or program there is never talked to.
tunnel_up() {
	local pid
	for pid in $(lsof -t -nP -iTCP@127.0.0.1:"$DEVTOOLS_MAC" -sTCP:LISTEN 2>/dev/null || true); do
		command ps -o command= -p "$pid" | grep -F -- "ssh -i $KEY " | grep -F -- "-p $PORT $USER_NAME@$HOST " |
			grep -qF -- "-L $DEVTOOLS_FORWARD" && return 0
	done
	return 1
}

cmd=${1:-}
shift || true
case "$cmd" in
	""|help|-h|--help) sed -n '2,44p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
	format) [ $# -eq 0 ] || [ "$*" = "--check" ] || { echo "usage: tools/vm format [--check]" >&2; exit 2; } ;;
esac
resolve_target
case "$cmd" in
	setup) setup "${1:-}" ;;
	status) status ;;
	sync) sync ;;
	format) format "${1:-}" ;;
	test) sync; ps "Set-Location '$REMOTE'; & '$DOTNET' test Pi.Core.Tests -v:minimal -nologo; if (\$LASTEXITCODE) { exit \$LASTEXITCODE }" ;;
	build) build ;;
	ui-test) ui_test "${1:-}" ;;
	run) run ;;
	dev) build; run ;;
	stop) stop ;;
	publish) check_rid "${1:-}"; lock publish; publish "${1:-}"; unlock ;;
	measure) measure "${1:-}" "${2:-}" ;;
	shot) shot "${1:-}" ;;
	page-shot) tunnel; node "$HERE/cdp.mjs" "$DEVTOOLS_MAC" screenshot "${1:-/tmp/win11-page.png}" ;;
	eval) [ -n "${1:-}" ] || { echo "usage: tools/vm eval '<js>'" >&2; exit 2; }; tunnel; node "$HERE/cdp.mjs" "$DEVTOOLS_MAC" eval "$1" ;;
	input) sync; ps "$ARCH; \$exe = $EXE
C:\\Tools\\desktop-run.ps1 -Exe powershell.exe -Arguments '-NoProfile -ExecutionPolicy Bypass -File $REMOTE\\tools\\input.ps1 $*' -Env ('PI_APP=' + \$exe) -Wait -TimeoutSec 60; exit \$LASTEXITCODE" ;;
	trace) trace "${1:-10}" ;;
	ps) ps "$1" ;;
	ssh) exec "${SSH[@]}" ;;
	*) echo "unknown command: $cmd (tools/vm help)" >&2; exit 2 ;;
esac
