@echo off
rem Lynn Preview - Windows double-click installer (lynn-installer.cmd).
rem
rem   *** NOTHING HERE MAY EVER SHOW A CONSOLE WINDOW. ***
rem
rem Double-clicking this file makes cmd.exe pop up a console window. That window
rem used to be the entire Windows experience: a black box that went quiet for
rem minutes and - when a tool underneath decided to read stdin - sat there until
rem somebody pressed Enter. So this file does exactly two things:
rem
rem   1. starts a windowless PowerShell (-WindowStyle Hidden -sta);
rem   2. that PowerShell puts up Lynn's own window and does all the work there.
rem
rem The user sees only Lynn's window: a title, one line of status at a time, and
rem a button only when there is something to decide. No scrollback, no prompt.
rem (Same shape as mac's installer.app + its log-view window.)
rem
rem Nothing in this file is ever printed: the console exists for a few hundred
rem milliseconds and is closed as soon as PowerShell has started. That is why
rem the failure paths below must not "echo" - there is nobody to read them. They
rem raise a message box instead (a dialog IS the window when there is no window
rem yet) and leave the reason in %TEMP%\lynn-installer-error.txt.
rem
rem Keep this file ASCII-only: cmd.exe decodes .cmd in the console codepage
rem (936 on a Chinese Windows), so any UTF-8 text would print as mojibake.
setlocal

if "%USERPROFILE%"=="" goto :lynn_no_powershell
where powershell >nul 2>nul || goto :lynn_no_powershell
rem The facts the entry script needs, handed over as environment variables so the
rem inline PowerShell below stays short and quoting-safe.
rem https, not http: the server answers every http request with a 301 (308 on the
rem git side), and Invoke-WebRequest refuses permanent redirects - the user saw
rem "remote server returned an error: (308) Permanent Redirect" in this very box.
rem A redirect is not something a downloader may decline, so ask for the final
rem address directly.
set "LYNN_INSTALL_URL=https://git.ghostinshells.com/lynn/lynn/raw/branch/main/deploy/windows/install.ps1"
set "LYNN_DIR=%USERPROFILE%\lynn"
set "LYNN_ENTRY=%~dp0"
set "LYNN_FIRST_MILE=%~dp0first-mile.ps1"

rem -sta: WinForms / tkinter need a single-threaded apartment to build a window.
rem -WindowStyle Hidden: no console at all - that is the whole point of this file.
rem start "" /b: do not wait. The command window closes as soon as the last
rem command in this script returns; it must not sit there behind Lynn's window.
rem
rem The entry is always first-mile.ps1, never installer.ps1: it draws the window
rem first and only then decides (through installer.ps1) whether this is a fresh
rem install or an upgrade, so the "already installed" case is covered without a
rem console and without a Read-Host nobody could answer.
rem
rem first-mile.ps1 is not guaranteed to sit next to this .cmd. The download page
rem used to hand out this file alone, and the hidden PowerShell then died on
rem "Cannot find path ...first-mile.ps1" with nobody to read it: no console, no
rem dialog, no window - the user's whole experience was "I double-clicked and
rem nothing happened". So the entry is resolved in three places, cheapest first:
rem
rem   1. next to this .cmd (a folder unpacked from the download page);
rem   2. inside the install tree (%USERPROFILE%\lynn\deploy\windows\entry),
rem      which is the already-installed machine;
rem   3. downloaded from the same raw branch install.ps1 comes from - the URL is
rem      LYNN_INSTALL_URL with "install.ps1" swapped for "entry/first-mile.ps1" -
rem      into %TEMP%\lynn-first-mile, which is the lone-.cmd machine.
rem
rem The last step is the important one for double-clicking a freshly downloaded
rem file, and every failure of it is reported in a dialog: silence is the bug.
start "" /b powershell -NoProfile -ExecutionPolicy Bypass -sta -WindowStyle Hidden -Command ^
  "$ErrorActionPreference='Stop';" ^
  "function Show-LynnError([string]$m) {" ^
  "  try { $m | Out-File -LiteralPath (Join-Path $env:TEMP 'lynn-installer-error.txt') -Encoding UTF8 } catch { }" ^
  "  try { Add-Type -AssemblyName System.Windows.Forms;" ^
  "    [void][System.Windows.Forms.MessageBox]::Show($m, 'Lynn'," ^
  "      [System.Windows.Forms.MessageBoxButtons]::OK," ^
  "      [System.Windows.Forms.MessageBoxIcon]::Error) } catch { }" ^
  "}" ^
  "try {" ^
  "  $entry = $env:LYNN_FIRST_MILE;" ^
  "  if (-not (Test-Path -LiteralPath $entry)) {" ^
  "    $entry = Join-Path $env:LYNN_DIR 'deploy\windows\entry\first-mile.ps1' }" ^
  "  if (-not (Test-Path -LiteralPath $entry)) {" ^
  "    $url = $env:LYNN_INSTALL_URL -replace 'install\.ps1$', 'entry/first-mile.ps1';" ^
  "    if (-not $url -or $url -eq $env:LYNN_INSTALL_URL) {" ^
  "      throw ('LYNN_INSTALL_URL does not name install.ps1: ' + $env:LYNN_INSTALL_URL) }" ^
  "    $dir = Join-Path $env:TEMP 'lynn-first-mile';" ^
  "    New-Item -ItemType Directory -Force -Path $dir | Out-Null;" ^
  "    $entry = Join-Path $dir 'first-mile.ps1';" ^
  "    Invoke-WebRequest -Uri $url -UseBasicParsing -OutFile $entry -TimeoutSec 60;" ^
  "    $body = Get-Content -Raw -Encoding UTF8 -LiteralPath $entry;" ^
  "    if (-not $body -or $body -notmatch 'ShowDialog' -or $body -notmatch 'LynnStage') {" ^
  "      throw ('what came back from ' + $url + ' is not first-mile.ps1') }" ^
  "  }" ^
  "  & ([scriptblock]::Create((Get-Content -Raw -Encoding UTF8 -LiteralPath $entry)))" ^
  "} catch {" ^
  "  Show-LynnError ('Lynn could not start its installer.' + [Environment]::NewLine + [Environment]::NewLine + $_.Exception.Message + [Environment]::NewLine + [Environment]::NewLine + 'Check the network connection, then double-click lynn-installer.cmd again.')" ^
  "}"
exit /b 0

:lynn_no_powershell
rem No USERPROFILE (or no powershell.exe) means there is no window to draw and
rem nothing to run. The only thing left that a person can see is a message box.
if exist "%SystemRoot%\System32\mshta.exe" (
    start "" /b "%SystemRoot%\System32\mshta.exe" "javascript:alert('Lynn needs Windows 10 or newer. This machine has no PowerShell.');close()"
)
exit /b 1
