-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.ps1
More file actions
1151 lines (1058 loc) · 50.9 KB
/
Copy pathinstall.ps1
File metadata and controls
1151 lines (1058 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Catalyst Code installer for Windows - TUI + optional web service.
.DESCRIPTION
DEFAULT: download the prebuilt standalone catcode.exe (Rust core embedded)
from GitHub Releases and put it on your user PATH - no compiler, no admin.
With -WithWeb, also download catcode-core.exe + the prebuilt web bundle and
install the web frontend as a Windows Service (NSSM) or a logon Scheduled
Task (web install is inlined in this script - same as install.sh --with-web).
No download needed - pipe it straight from the web:
irm https://raw.githubusercontent.com/catalystctl/catcode/master/install.ps1 | iex
Run with no parameters in an interactive terminal to get a menu
(install, install with web, add web, update, reinstall, uninstall, status).
With arguments (e.g. -WithWeb), use the scriptblock form:
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/catalystctl/catcode/master/install.ps1))) -WithWeb
Or from a repo clone:
pwsh -ExecutionPolicy Bypass -File .\install.ps1
pwsh -ExecutionPolicy Bypass -File .\install.ps1 -WithWeb
.PARAMETER Version
Pin a release (e.g. "0.2.0" or "v0.2.0"). Default: latest.
.PARAMETER BaseUrl
Download base URL override (default: GitHub Releases for the resolved tag).
.PARAMETER InstallDir
Where catcode.exe + catcode-core.exe are installed. Default:
%LOCALAPPDATA%\Programs\catcode (per-user, no admin).
.PARAMETER WithWeb
Also install the web frontend service (downloads catcode-core.exe + the
prebuilt web bundle; sets up an NSSM service or a Scheduled Task).
.PARAMETER Port
Web service port. Default 49283.
.PARAMETER BindHost
Web bind host. Default 0.0.0.0 (use 127.0.0.1 + a reverse proxy for public use).
.PARAMETER WebDir
Where to extract the web bundle. Default %LOCALAPPDATA%\catalyst-code\web.
.PARAMETER Update
Re-download the latest release and reinstall (also restarts the web service
if it was previously installed).
.PARAMETER Uninstall
Stop + remove catcode, catcode-core, the web service/task, and install state.
.PARAMETER AddWeb
Add the web service to an existing install (installs catcode-core.exe + the
prebuilt web bundle + service/task). Pins to the installed version unless
-Version is given.
.PARAMETER Reinstall
Reinstall the currently-installed version (re-downloads the same release).
.PARAMETER Status
Show the current install state (version, paths, web on/off) and exit.
.PARAMETER DryRun
Print the plan, execute nothing.
.PARAMETER NoColor
Disable colored output.
.EXAMPLE
.\install.ps1 # interactive menu + optional settings prompts
.\install.ps1 -WithWeb -Port 8080 -BindHost 127.0.0.1
.\install.ps1 -Version 0.2.0
.\install.ps1 -Update
.\install.ps1 -AddWeb
.\install.ps1 -Reinstall
.\install.ps1 -Uninstall
.\install.ps1 -Status
#>
[CmdletBinding()]
param(
[string]$Version = '',
[string]$BaseUrl = '',
[string]$InstallDir = '',
[switch]$WithWeb,
[int]$Port = 49283,
[string]$BindHost = '0.0.0.0',
[string]$WebDir = '',
[string]$Expose = 'intranet',
[string]$Origin = '',
[string]$Workspace = '',
[string]$Shell = '',
[string]$IdleGcMs = '',
[string]$InstallerUrl = '',
[string]$WindowsInstallerUrl = '',
[string]$TrustedOrigins = '',
[switch]$Update,
[switch]$Uninstall,
[switch]$AddWeb,
[switch]$Reinstall,
[switch]$Status,
[switch]$DryRun,
[switch]$NoColor,
[switch]$Help
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue' # speed up Invoke-WebRequest on large .exe
# -- constants + env-derived defaults (resolved in the body so a missing --
# LOCALAPPDATA never crashes param binding; on Windows it is always set for
# user sessions, but SYSTEM/service accounts may lack it).
$Repo = 'catalystctl/catcode'
$Arch = 'x86_64'
function Resolve-LocalAppData {
if ($env:LOCALAPPDATA) { return $env:LOCALAPPDATA }
if ($env:USERPROFILE) { return Join-Path $env:USERPROFILE 'AppData\Local' }
return $env:HOME # non-Windows / fallback
}
$DataDir = Join-Path (Resolve-LocalAppData) 'catalyst-code'
$StateFile = Join-Path $DataDir 'installer.state'
if (-not $InstallDir) { $InstallDir = Join-Path (Resolve-LocalAppData) 'Programs\catcode' }
if (-not $WebDir) { $WebDir = Join-Path $DataDir 'web' }
# mirror the -WithWeb switch into a script-scoped flag (so -Update can set it
# from the recorded install state).
$script:WithWeb = [bool]$WithWeb
# -- web-service env knobs (resolved at install time; empty = omit from env) --
$script:Expose = $Expose
$script:ResolvedOrigin = ''
$script:OriginOverride = $Origin
$script:Workspace = $Workspace
$script:ShellVar = $Shell # stamped as SHELL=...
$script:IdleGcMs = $IdleGcMs
$script:InstallerUrl = $InstallerUrl
$script:WinInstallerUrl = $WindowsInstallerUrl
$script:TrustedOrigins = $TrustedOrigins
$script:ResolvedHost = '' # bind host derived from -Expose/-BindHost
# which params were explicitly passed (so update/reinstall/add-web restore the
# rest from saved state instead of falling back to param defaults).
$CliParams = @{}; foreach ($k in $PSBoundParameters.Keys) { $CliParams[$k] = $true }
# loaded install state (null for a fresh install); Finalize-WebEnv restores
# saved env values from it so an update keeps the installed config.
$script:State = $null
# -- helpers --------------------------------------------------
function W-Info($t) { if ($NoColor) { Write-Host " $t" } else { Write-Host " $t" -ForegroundColor Cyan } }
function W-Ok($t) { if ($NoColor) { Write-Host " $t" } else { Write-Host " $t" -ForegroundColor Green } }
function W-Warn($t){ if ($NoColor) { Write-Host " $t" } else { Write-Host " $t" -ForegroundColor Yellow } }
# Prefer throw over exit: under `irm | iex` or `& ([scriptblock]::Create(...))`,
# exit kills the user's entire PowerShell window so they never see the error.
# throw surfaces a red error and leaves the shell open. `pwsh -File` still
# exits non-zero on an uncaught throw (CI/scripted use stays correct).
function Die($t) { Write-Host "`n error: $t" -ForegroundColor Red; throw "install failed: $t" }
# Native exes (schtasks/sc/nssm) write expected failures to stderr. With
# $ErrorActionPreference=Stop, PowerShell turns that into a terminating
# NativeCommandError even when redirected - so "task not found" on first
# install aborts the script. Run them under Continue and use $LASTEXITCODE.
function Invoke-Native {
param(
[Parameter(Mandatory)][string]$FilePath,
[Parameter(ValueFromRemainingArguments)][string[]]$ArgumentList
)
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& $FilePath @ArgumentList *> $null
return $LASTEXITCODE
} finally {
$ErrorActionPreference = $prev
}
}
function Show-Help {
$usage = @"
Catalyst Code - installer for Windows
Usage:
pwsh -ExecutionPolicy Bypass -File .\install.ps1 [options]
irm https://raw.githubusercontent.com/catalystctl/catcode/master/install.ps1 | iex
& ([scriptblock]::Create((irm .../install.ps1))) -WithWeb
Options:
-Version <v> pin a release (e.g. "0.2.0" or "v0.2.0") default: latest
-BaseUrl <url> download from a mirror instead of GitHub Releases
-InstallDir <path> binary install dir (default: %LOCALAPPDATA%\Programs\catcode)
-WithWeb also install the web frontend service
-Port <n> web service port (default: 49283)
-BindHost <h> web bind host (default: 0.0.0.0)
-Expose <mode> CORS/exposure: local|intranet|public (default: intranet)
-Origin <url> canonical origin (CATCODE_WEB_ORIGIN); overrides -Expose
-Workspace <path> default workspace the core opens
-Shell <path> terminal shell for the web terminal
-IdleGcMs <n> idle live-session GC interval ms (0=disable)
-InstallerUrl <u> self-update install.sh URL
-WindowsInstallerUrl <u> self-update install.ps1 URL
-TrustedOrigins <list> additional trusted origins for better-auth CSRF (BETTER_AUTH_TRUSTED_ORIGINS,
comma-separated; for a proxy/multi-domain setup)
-WebDir <path> web bundle install dir (default: %LOCALAPPDATA%\catalyst-code\web)
-AddWeb add the web service to an existing install
-Update re-download latest + reinstall (+ restart the web service)
-Reinstall reinstall the currently-installed version
-Uninstall stop + remove binaries, service, and state
-Status show the current install state
-DryRun print the plan, execute nothing
-NoColor disable colored output
-Help show this help
"@
Write-Host $usage
}
# -- release resolution + asset download (mirrors install.sh) -
# Strip a leading "v" from a tag for the version string used in asset names.
# Unlike Substring(1), this leaves commit-SHA tags (e.g. "1c08256") intact.
function Get-VerFromTag {
param([string]$Tag)
if ($Tag.StartsWith('v') -or $Tag.StartsWith('V')) { return $Tag.Substring(1) }
return $Tag
}
function Resolve-Release {
if ($Version) {
# Accept "0.2.0" (-> v0.2.0 semver tag), "v0.2.0" (as-is), or a commit
# SHA like "1c08256" (as-is - SHA tags have no leading v). Only prepend v
# for bare semver (digits.digits), never for hex SHAs.
$script:Tag = $Version
if ($script:Tag -match '^[0-9]+\.[0-9]+' -and -not $script:Tag.StartsWith('v')) {
$script:Tag = "v$($script:Tag)"
}
$script:Ver = Get-VerFromTag $script:Tag
} else {
$api = "https://api.github.com/repos/$Repo/releases/latest"
try {
$rel = Invoke-RestMethod -Uri $api -Headers @{ 'User-Agent' = 'catcode-installer' } -ErrorAction Stop
$script:Tag = $rel.tag_name
$script:Ver = Get-VerFromTag $script:Tag
} catch {
Die "could not resolve the latest release from $api.`n The repo may be private or rate-limited. Pass -Version <v> (e.g. -Version 0.2.0) or -BaseUrl <url> to a public mirror."
}
}
if ($BaseUrl) {
$script:Base = $BaseUrl.TrimEnd('/')
} else {
$script:Base = "https://github.com/$Repo/releases/download/$($script:Tag)"
}
}
# -- web-service env: exposure mode + origin + bind ---------------
# Primary non-loopback IPv4 (for -Expose intranet's auto-origin). Returns $null on failure.
function Get-LanIp {
try {
# prefer the interface that actually has a default gateway (the real LAN)
$ip = (Get-NetIPConfiguration -ErrorAction Stop |
Where-Object { $_.IPv4DefaultGateway } |
Select-Object -First 1).IPv4Address.IPAddress
if ($ip -and $ip -ne '127.0.0.1' -and $ip -notlike '169.254.*') { return $ip }
} catch {}
try {
$ip = (Get-NetIPAddress -AddressFamily IPv4 -ErrorAction Stop |
Where-Object { $_.IPAddress -ne '127.0.0.1' -and $_.PrefixOrigin -ne 'WellKnown' } |
Select-Object -First 1).IPAddress
if ($ip -and $ip -ne '127.0.0.1') { return $ip }
} catch {}
return $null
}
# Derive bind $script:ResolvedHost + canonical $script:ResolvedOrigin from $script:Expose
# (+ -BindHost / -Origin overrides). Mirrors install.sh resolve_expose().
function Resolve-Expose {
if ($CliParams.ContainsKey('BindHost') -and $BindHost) {
$script:ResolvedHost = $BindHost
} elseif ($script:Expose -eq 'local') {
$script:ResolvedHost = '127.0.0.1'
} elseif ($script:Expose -eq 'intranet' -or $script:Expose -eq 'public') {
$script:ResolvedHost = '0.0.0.0'
} else {
Die "unknown -Expose mode: $($script:Expose) (use local|intranet|public)"
}
if ($script:OriginOverride) {
$script:ResolvedOrigin = $script:OriginOverride
} elseif ($script:Expose -eq 'local') {
$script:ResolvedOrigin = "http://localhost:$Port"
} elseif ($script:Expose -eq 'intranet') {
$lan = Get-LanIp
if ($lan) {
$script:ResolvedOrigin = "http://${lan}:$Port"
} else {
$script:ResolvedOrigin = "http://localhost:$Port"
W-Warn "could not auto-detect a LAN IP for -Expose intranet; non-loopback auth will fail until you set -Origin http://<lan-ip>:$Port"
}
} elseif ($script:Expose -eq 'public') {
Die '-Expose public requires -Origin <url> (your public/tunnel URL, e.g. https://code.example.com)'
}
}
# Restore saved env values from state for params NOT passed on this run, then
# derive bind+origin. Mirrors install.sh finalize_web_env(). $st may be $null
# (fresh install). No-op when the web service is not in scope.
function Finalize-WebEnv($st) {
if (-not $script:WithWeb) { return }
if ($st) {
if (-not $CliParams.ContainsKey('Port') -and $st.port) { $script:Port = $st.port }
if (-not $CliParams.ContainsKey('Expose') -and $st.expose) { $script:Expose = $st.expose }
if (-not $CliParams.ContainsKey('Origin') -and $st.origin_override){ $script:OriginOverride = $st.origin_override }
if (-not $CliParams.ContainsKey('Origin') -and $st.origin) { $script:ResolvedOrigin = $st.origin }
if (-not $CliParams.ContainsKey('Workspace') -and $st.workspace) { $script:Workspace = $st.workspace }
if (-not $CliParams.ContainsKey('Shell') -and $st.shell) { $script:ShellVar = $st.shell }
if (-not $CliParams.ContainsKey('IdleGcMs') -and $st.idle_gc_ms) { $script:IdleGcMs = $st.idle_gc_ms }
if (-not $CliParams.ContainsKey('InstallerUrl') -and $st.installer_url) { $script:InstallerUrl = $st.installer_url }
if (-not $CliParams.ContainsKey('WindowsInstallerUrl') -and $st.windows_installer_url) { $script:WinInstallerUrl = $st.windows_installer_url }
if (-not $CliParams.ContainsKey('TrustedOrigins') -and $st.trusted_origins) { $script:TrustedOrigins = $st.trusted_origins }
if (-not $CliParams.ContainsKey('BindHost') -and $st.host) { $script:ResolvedHost = $st.host }
}
# (Re-)derive bind+origin when a CLI override is present, or when no
# resolved origin exists yet (fresh install / old state). A plain update
# keeps the previously-resolved ORIGIN+HOST so a stable install doesn't churn.
if ($script:OriginOverride -or $CliParams.ContainsKey('Expose') -or $CliParams.ContainsKey('BindHost') -or -not $script:ResolvedOrigin) {
Resolve-Expose
}
}
# KEY=value strings for the service env block (NSSM AppEnvironmentExtra / task `set`).
function Get-EnvPairs {
$pairs = @('NODE_ENV=production', "PORT=$Port", "HOSTNAME=$($script:ResolvedHost)", "CATCODE_CORE=$script:CoreExe")
if ($script:ResolvedOrigin) { $pairs += "CATCODE_WEB_ORIGIN=$($script:ResolvedOrigin)" }
if ($script:Workspace) { $pairs += "CATALYST_CODE_WORKSPACE=$($script:Workspace)" }
if ($script:ShellVar) { $pairs += "SHELL=$($script:ShellVar)" }
if ($script:IdleGcMs) { $pairs += "UMANS_WEB_IDLE_GC_MS=$($script:IdleGcMs)" }
if ($script:InstallerUrl) { $pairs += "CATCODE_INSTALLER_URL=$($script:InstallerUrl)" }
if ($script:WinInstallerUrl){ $pairs += "CATCODE_WINDOWS_INSTALLER_URL=$($script:WinInstallerUrl)" }
if ($script:TrustedOrigins) { $pairs += "BETTER_AUTH_TRUSTED_ORIGINS=$($script:TrustedOrigins)" }
return $pairs
}
# download <Base>/<Name> + <Name>.sha256, verify the checksum. Returns the file path.
function Get-Asset {
param([string]$Name)
$url = "$($script:Base)/$Name"
$tmp = $env:TEMP
if (-not $tmp) { $tmp = $env:TMP }
if (-not $tmp) { $tmp = $env:TMPDIR }
if (-not $tmp) { $tmp = [System.IO.Path]::GetTempPath() }
if (-not $tmp) { Die 'no temp directory (TEMP/TMP unset)' }
$dest = Join-Path $tmp $Name
W-Info "Downloading $Name ..."
try {
Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing
} catch {
Die "download failed: $url`n $($_.Exception.Message)"
}
try {
Invoke-WebRequest -Uri "$url.sha256" -OutFile "$dest.sha256" -UseBasicParsing
} catch {
Die "checksum download failed: $url.sha256"
}
$expected = (Get-Content "$dest.sha256" -Raw).Trim().Split(' ')[0].ToLower()
$actual = (Get-FileHash $dest -Algorithm SHA256).Hash.ToLower()
if ($expected -ne $actual) { Die "checksum mismatch for $Name (expected $expected, got $actual)" }
W-Ok "Verified $Name"
return $dest
}
# -- PATH management -----------------------------------------
function Add-ToPath {
$path = [Environment]::GetEnvironmentVariable('Path', 'User')
if (-not $path) { $path = '' }
$parts = @($path.Split(';') | Where-Object { $_ -ne '' })
# Case-insensitive compare so we don't double-add with different casing.
$already = $false
foreach ($p in $parts) {
if ([string]::Equals($p, $InstallDir, [System.StringComparison]::OrdinalIgnoreCase)) {
$already = $true
break
}
}
if (-not $already) {
$newPath = (($parts + $InstallDir) -join ';')
[Environment]::SetEnvironmentVariable('Path', $newPath, 'User')
W-Ok "Added $InstallDir to your user PATH."
} else {
W-Ok "$InstallDir is already on your user PATH."
}
# refresh the current session so `catcode` works immediately
if ($env:Path -notlike "*$InstallDir*") { $env:Path = "$env:Path;$InstallDir" }
}
function Remove-FromPath {
$path = [Environment]::GetEnvironmentVariable('Path', 'User')
if (-not $path) { return }
$parts = @($path.Split(';') | Where-Object {
$_ -ne '' -and -not [string]::Equals($_, $InstallDir, [System.StringComparison]::OrdinalIgnoreCase)
})
$newPath = ($parts -join ';')
if ($newPath -ne $path) {
[Environment]::SetEnvironmentVariable('Path', $newPath, 'User')
W-Ok "Removed $InstallDir from your user PATH."
}
# Best-effort: drop from the current session PATH too.
$sessionParts = @($env:Path.Split(';') | Where-Object {
$_ -ne '' -and -not [string]::Equals($_, $InstallDir, [System.StringComparison]::OrdinalIgnoreCase)
})
$env:Path = ($sessionParts -join ';')
}
# -- TUI install (download standalone catcode.exe) ------------
function Install-Tui {
if (-not (Test-Path -LiteralPath $InstallDir)) {
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
}
$tuiAsset = "catcode-$($script:Ver)-windows-$Arch.exe"
$src = Get-Asset $tuiAsset
Copy-Item -LiteralPath $src -Destination (Join-Path $InstallDir 'catcode.exe') -Force
W-Ok "Installed catcode.exe -> $InstallDir\catcode.exe"
Add-ToPath
}
# -- separate core binary for the web service's CATCODE_CORE --
function Install-CoreForWeb {
$coreAsset = "catcode-core-$($script:Ver)-windows-$Arch.exe"
$src = Get-Asset $coreAsset
Copy-Item -LiteralPath $src -Destination (Join-Path $InstallDir 'catcode-core.exe') -Force
W-Ok "Installed catcode-core.exe -> $InstallDir\catcode-core.exe"
}
# --- web service (inlined - formerly packaging/windows/install-web.ps1) ---
$SvcName = 'CatalystCodeWeb'
$TaskName = 'CatalystCodeWeb'
$WrapperPath = Join-Path $DataDir 'run-web.cmd'
$LogPath = Join-Path $DataDir 'catalyst-code-web.log'
$script:RT = $null
$script:RTExe = $null
function Detect-Runtime {
# Authentication uses node:sqlite, so Bun is not a compatible server
# runtime even though it can install dependencies and run unit tests.
$node = Get-Command node -ErrorAction SilentlyContinue
if ($node) {
$nodeVer = (& node --version) -replace '^v',''
if ([version]$nodeVer -lt [version]'22.13.0') {
Die "Node.js >= 22.13.0 is required (found v${nodeVer}); the web frontend uses node:sqlite"
}
$script:RT = 'node'; $script:RTExe = $node.Source; return
}
Die 'Node.js >= 22.13.0 is required to run the web frontend (https://nodejs.org)'
}
# --- resolve release version + base URL ------------------------------------
# Strip a leading "v" from a tag for the version string used in asset names.
# Unlike Substring(1), this leaves commit-SHA tags (e.g. "1c08256") intact.
function Assert-WebBundle {
param([string]$Dir)
$startJs = Join-Path $Dir 'start.js'
if (-not (Test-Path -LiteralPath $startJs)) { Die "web bundle missing start.js (extraction failed?)" }
if (-not (Test-Path -LiteralPath (Join-Path $Dir 'server.js'))) { Die 'web bundle missing server.js' }
if (-not (Test-Path -LiteralPath (Join-Path $Dir 'package.json'))) {
Die 'web bundle missing package.json (incomplete release artifact)'
}
if (-not (Test-Path -LiteralPath (Join-Path $Dir '.next\BUILD_ID'))) {
Die 'web bundle missing .next/BUILD_ID (incomplete release artifact)'
}
if ((Test-Path -LiteralPath (Join-Path $Dir 'web\server.js')) -or
(Test-Path -LiteralPath (Join-Path $Dir 'web\node_modules'))) {
Die @"
web bundle has nested web/ layout - this release artifact was packed incorrectly.
Use a newer catcode-web-*.tar.gz built by current release-web.sh.
"@
}
foreach ($req in @('next', 'ws', 'zigpty', 'better-auth')) {
$pkg = Join-Path $Dir "node_modules\$req\package.json"
if (-not (Test-Path -LiteralPath $pkg)) {
Die "web bundle missing node_modules/$req - incomplete release artifact (custom server cannot start)."
}
}
if (-not (Test-Path -LiteralPath (Join-Path $Dir 'version.json'))) {
Die 'web bundle missing version.json (git commit not embedded)'
}
W-Ok "Web bundle looks runnable ($Dir)"
}
function Stop-WebService {
$nssm = Get-Command nssm -ErrorAction SilentlyContinue
if ($nssm) { [void](Invoke-Native $nssm.Source stop $SvcName) }
[void](Invoke-Native sc.exe stop $SvcName)
if ((Invoke-Native schtasks /query /tn $TaskName) -eq 0) {
[void](Invoke-Native schtasks /end /tn $TaskName)
}
}
function Start-ExistingWebService {
$nssm = Get-Command nssm -ErrorAction SilentlyContinue
if ($nssm -and (Invoke-Native $nssm.Source start $SvcName) -eq 0) { return }
if ((Invoke-Native sc.exe start $SvcName) -eq 0) { return }
if ((Invoke-Native schtasks /query /tn $TaskName) -eq 0) {
[void](Invoke-Native schtasks /run /tn $TaskName)
}
}
function Install-WebBundle {
# Universal cross-platform tarball (same asset Linux/macOS/Windows installers fetch).
$tgz = Get-Asset "catcode-web-$($script:Ver).tar.gz"
$parent = Split-Path -Parent $WebDir
if (-not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
$stage = Join-Path $parent ('.web-update-' + [guid]::NewGuid().ToString('N'))
$backup = "$WebDir.old"
New-Item -ItemType Directory -Path $stage -Force | Out-Null
try {
# Windows 10+ ships tar (bsdtar); it handles .tar.gz natively.
$tar = Get-Command tar -ErrorAction SilentlyContinue
if (-not $tar) { Die 'tar not found (Windows 10 1803+ ships it). Extract the .tar.gz manually or install tar.' }
W-Info "Extracting web bundle -> $stage ..."
& tar -xzf $tgz -C $stage
if ($LASTEXITCODE -ne 0) { Die "tar extraction failed (exit $LASTEXITCODE)" }
Write-WebVersionJson -Dir $stage -Commit $script:Ver -Source 'release'
Assert-WebBundle -Dir $stage
Remove-Item -LiteralPath $backup -Recurse -Force -ErrorAction SilentlyContinue
$promoted = $false
for ($attempt = 0; $attempt -lt 10 -and -not $promoted; $attempt++) {
try {
if (Test-Path -LiteralPath $WebDir) { Move-Item -LiteralPath $WebDir -Destination $backup -ErrorAction Stop }
Move-Item -LiteralPath $stage -Destination $WebDir -ErrorAction Stop
$promoted = $true
} catch {
if ((Test-Path -LiteralPath $backup) -and -not (Test-Path -LiteralPath $WebDir)) {
Move-Item -LiteralPath $backup -Destination $WebDir -ErrorAction SilentlyContinue
}
if (-not $promoted) { Start-Sleep -Milliseconds 500 }
}
}
if (-not $promoted) { Die 'web bundle is still in use; close the web service and retry' }
Remove-Item -LiteralPath $backup -Recurse -Force -ErrorAction SilentlyContinue
W-Ok "Web bundle extracted to $WebDir"
} finally {
Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
}
}
function Write-WebVersionJson {
param(
[string]$Dir,
[string]$Commit,
[string]$Source = 'release'
)
$builtAt = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
$payload = [ordered]@{
commit = $Commit
commitFull = $Commit
dirty = $false
builtAt = $builtAt
source = $Source
}
$json = $payload | ConvertTo-Json
$path = Join-Path $Dir 'version.json'
Set-Content -LiteralPath $path -Value $json -Encoding UTF8
$nextDir = Join-Path $Dir '.next'
if (Test-Path -LiteralPath $nextDir) {
Set-Content -LiteralPath (Join-Path $nextDir 'version.json') -Value $json -Encoding UTF8
}
W-Ok "Web version: $Commit ($Source)"
}
# --- NSSM service -----------------------------------------------------------
function Install-NssmService {
$nssm = Get-Command nssm -ErrorAction SilentlyContinue
if (-not $nssm) { return $false }
$nssm = $nssm.Source
[void](Invoke-Native $nssm stop $SvcName)
[void](Invoke-Native $nssm remove $SvcName confirm)
W-Info "Installing Windows Service '$SvcName' (NSSM)..."
& $nssm install $SvcName $RTExe (Join-Path $WebDir 'start.js') *> $null
if ($LASTEXITCODE -ne 0) { Die "nssm install failed (exit $LASTEXITCODE)" }
& $nssm set $SvcName AppDirectory $WebDir *> $null
$envPairs = Get-EnvPairs
& $nssm set $SvcName AppEnvironmentExtra $envPairs *> $null
& $nssm set $SvcName AppStdout $LogPath *> $null
& $nssm set $SvcName AppStderr $LogPath *> $null
& $nssm set $SvcName AppRotateFiles 1 *> $null
& $nssm set $SvcName AppRotateBytes 10485760 *> $null
& $nssm set $SvcName AppRestartDelay 3000 *> $null
& $nssm set $SvcName Start 'SERVICE_AUTO_START' *> $null
& $nssm start $SvcName *> $null
if ($LASTEXITCODE -ne 0) { Die "nssm start failed - check: nssm get $SvcName AppStdout ; Get-Content $LogPath" }
W-Ok "Service '$SvcName' installed and started (NSSM, auto-start at boot)"
return $true
}
# --- scheduled-task fallback (zero-dependency) ------------------------------
function Write-Wrapper {
# restart-loop wrapper: re-launches `node start.js` 3s after it exits.
$setLines = Get-EnvPairs | ForEach-Object { "set $_" }
$cmd = (@('@echo off') + $setLines + @(
':loop',
"cd /d `"$WebDir`"",
"`"$RTExe`" `"$WebDir\start.js`"",
'echo [%date% %time%] web exited, restarting in 3s...',
'timeout /t 3 /nobreak >nul',
'goto loop'
)) -join "`r`n"
if (-not (Test-Path $DataDir)) { New-Item -ItemType Directory -Path $DataDir -Force | Out-Null }
[System.IO.File]::WriteAllText($WrapperPath, $cmd)
}
function Install-Task {
W-Info 'NSSM not found - installing as a Scheduled Task at logon...'
W-Warn 'Note: a Scheduled Task runs only while a user is logged in.'
W-Warn ' For a true boot-time service, install NSSM (https://nssm.cc) and re-run.'
Write-Wrapper
# /query fails with "file not found" when the task is absent - expected on first install.
if ((Invoke-Native schtasks /query /tn $TaskName) -eq 0) {
[void](Invoke-Native schtasks /delete /tn $TaskName /f)
}
$ec = Invoke-Native schtasks /create /tn $TaskName /tr "`"$WrapperPath`"" /sc onlogon /rl limited /f
if ($ec -ne 0) { Die "schtasks /create failed (exit $ec)" }
[void](Invoke-Native schtasks /run /tn $TaskName)
W-Ok "Scheduled task '$TaskName' created and started (at logon, restart-loop wrapper)"
}
# --- build-from-source fallback (old path) ---------------------------------
function Build-Web-FromSource {
Write-Host ''
Write-Host 'Building web frontend from source (SDK + Next.js)' -ForegroundColor Cyan
$rt = $null; $rtExe = $null
$bun = Get-Command bun -ErrorAction SilentlyContinue
if ($bun) { $rt = 'bun'; $rtExe = $bun.Source }
else {
$npm = Get-Command npm -ErrorAction SilentlyContinue
if ($npm) { $node = Get-Command node -ErrorAction SilentlyContinue; if (-not $node) { Die 'npm found but node is not on PATH' }; $rt = 'npm'; $rtExe = $npm.Source }
else { Die 'neither bun nor npm found (https://bun.sh or https://nodejs.org)' }
}
W-Ok "Runtime: $rt ($rtExe)"
Push-Location (Join-Path $RepoDir 'sdk')
try { & $rtExe install *> $null; if ($LASTEXITCODE -ne 0) { Die 'SDK dep install failed' }; & $rtExe run build *> $null; if ($LASTEXITCODE -ne 0) { Die 'SDK build failed' } }
finally { Pop-Location }
Push-Location (Join-Path $RepoDir 'web')
try { & $rtExe install *> $null; if ($LASTEXITCODE -ne 0) { Die 'web dep install failed' }; $env:NEXT_TELEMETRY_DISABLED = '1'; & $rtExe run build; if ($LASTEXITCODE -ne 0) { Die 'web build failed' } }
finally { Pop-Location }
# source path runs `next start` from the repo web dir
$script:WebDir = Join-Path $RepoDir 'web'
$script:RT = $rt; $script:RTExe = $rtExe
W-Ok 'Web build complete'
}
# --- uninstall --------------------------------------------------------------
function Install-WebService {
Detect-Runtime
# Script-scoped so Install-NssmService / Write-Wrapper see CATCODE_CORE.
$script:CoreExe = Join-Path $InstallDir 'catcode-core.exe'
$CoreExe = $script:CoreExe
if (-not (Test-Path -LiteralPath $CoreExe)) {
Die "catcode-core.exe missing at $CoreExe - install core first"
}
Stop-WebService
try {
Install-WebBundle
} catch {
Start-ExistingWebService
throw
}
if (-not (Install-NssmService)) { Install-Task }
W-Ok "Web frontend service ready at http://localhost:$Port"
}
function Uninstall-WebService {
W-Info 'Removing web service ...'
$nssm = Get-Command nssm -ErrorAction SilentlyContinue
$removed = $false
if ($nssm) {
$nssm = $nssm.Source
[void](Invoke-Native $nssm stop $SvcName)
$ec = Invoke-Native $nssm remove $SvcName confirm
if ($ec -eq 0) { W-Ok "Removed Windows Service '$SvcName'"; $removed = $true }
} else {
[void](Invoke-Native sc.exe stop $SvcName)
[void](Invoke-Native sc.exe delete $SvcName)
}
if ((Invoke-Native schtasks /query /tn $TaskName) -eq 0) {
[void](Invoke-Native schtasks /end /tn $TaskName)
[void](Invoke-Native schtasks /delete /tn $TaskName /f)
W-Ok "Removed Scheduled Task '$TaskName'"; $removed = $true
}
if (Test-Path $WrapperPath) { Remove-Item $WrapperPath -Force; W-Ok "Removed wrapper $WrapperPath" }
if (Test-Path -LiteralPath $WebDir) {
Remove-Item -LiteralPath $WebDir -Recurse -Force -ErrorAction SilentlyContinue
W-Ok "Removed web bundle $WebDir"
}
if (-not $removed) { W-Warn 'No service or task found to remove (already clean?)' }
}
# -- install state --------------------------------------------
function Save-State([bool]$WebInstalled) {
$installedAt = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
$webFlag = if ($WebInstalled) { 'yes' } else { 'no' }
# NOTE: keep this as an assignment-RHS `if` (a statement). Do NOT inline it
# inside (...) as an operand (e.g. `('X=' + (if ...) + ...)`): in expression
# position PowerShell parses `if` as a COMMAND NAME and throws
# "The term 'if' is not recognized" at runtime under irm|iex AND pwsh -File.
$stateHost = if ($script:ResolvedHost) { $script:ResolvedHost } else { $BindHost }
$st = [ordered]@{
version = $script:Ver
with_web = $webFlag
install_dir = $InstallDir
web_dir = $WebDir
port = $Port
host = $stateHost
expose = $script:Expose
origin_override = $script:OriginOverride
origin = $script:ResolvedOrigin
workspace = $script:Workspace
shell = $script:ShellVar
idle_gc_ms = $script:IdleGcMs
installer_url = $script:InstallerUrl
windows_installer_url = $script:WinInstallerUrl
trusted_origins = $script:TrustedOrigins
installed_at = $installedAt
}
if (-not (Test-Path -LiteralPath $DataDir)) { New-Item -ItemType Directory -Path $DataDir -Force | Out-Null }
$st | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $DataDir 'installer.state.json') -Encoding UTF8
$shellLines = @(
'# Catalyst Code installer state - written by install.ps1',
'# (shell-sourcable; consumed by catcode --update)',
'METHOD="download"',
('PREFIX="' + $InstallDir + '"'),
('PORT="' + $Port + '"'),
('HOST="' + $stateHost + '"'),
('EXPOSE_MODE="' + $script:Expose + '"'),
('ORIGIN_OVERRIDE="' + $script:OriginOverride + '"'),
('ORIGIN="' + $script:ResolvedOrigin + '"'),
('WORKSPACE="' + $script:Workspace + '"'),
('TERM_SHELL="' + $script:ShellVar + '"'),
('IDLE_GC_MS="' + $script:IdleGcMs + '"'),
('INSTALLER_URL="' + $script:InstallerUrl + '"'),
('WIN_INSTALLER_URL="' + $script:WinInstallerUrl + '"'),
('TRUSTED_ORIGINS="' + $script:TrustedOrigins + '"'),
('WEB_DIR="' + $WebDir + '"'),
('WEB_INSTALLED="' + $webFlag + '"'),
'UNIT_NAME="CatalystCodeWeb"',
('VERSION="' + $script:Ver + '"'),
('INSTALLED_AT="' + $installedAt + '"')
)
Set-Content -LiteralPath $StateFile -Value ($shellLines -join "`r`n") -Encoding UTF8
W-Ok "Recorded install state -> $StateFile"
}
function Load-State {
if (-not (Test-Path -LiteralPath $StateFile)) { return $null }
$raw = Get-Content -LiteralPath $StateFile -Raw
try {
$j = $raw | ConvertFrom-Json
if ($null -ne $j.version -or $null -ne $j.with_web) { return $j }
} catch {}
$jsonBackup = Join-Path $DataDir 'installer.state.json'
if (Test-Path -LiteralPath $jsonBackup) {
try { return (Get-Content -LiteralPath $jsonBackup -Raw | ConvertFrom-Json) } catch {}
}
$map = @{}
foreach ($line in ($raw -split "`r?`n")) {
if ($line -match '^([A-Z_]+)="([^"]*)"') { $map[$Matches[1]] = $Matches[2] }
}
if (-not $map.ContainsKey('VERSION') -and -not $map.ContainsKey('WEB_INSTALLED')) { return $null }
return [pscustomobject]@{
version = $map['VERSION']
with_web = if ($map['WEB_INSTALLED']) { $map['WEB_INSTALLED'] } else { 'no' }
install_dir = if ($map['PREFIX']) { $map['PREFIX'] } else { $InstallDir }
web_dir = if ($map['WEB_DIR']) { $map['WEB_DIR'] } else { $WebDir }
port = if ($map['PORT']) { [int]$map['PORT'] } else { $Port }
host = if ($map['HOST']) { $map['HOST'] } else { $BindHost }
expose = $map['EXPOSE_MODE']
origin_override = $map['ORIGIN_OVERRIDE']
origin = $map['ORIGIN']
workspace = $map['WORKSPACE']
shell = $map['TERM_SHELL']
idle_gc_ms = $map['IDLE_GC_MS']
installer_url = $map['INSTALLER_URL']
windows_installer_url = $map['WIN_INSTALLER_URL']
trusted_origins = $map['TRUSTED_ORIGINS']
installed_at = $map['INSTALLED_AT']
}
}
# -- summaries ------------------------------------------------
function Summary-Install {
$webLine = if ($script:WithWeb) { "http://$($script:ResolvedHost):$Port (service: NSSM or Scheduled Task)" } else { '(not installed - re-run with -WithWeb)' }
Write-Host ''
Write-Host ' --------------------------------------------' -ForegroundColor Green
Write-Host ' OK Installed Catalyst Code v' -NoNewline -ForegroundColor Green
Write-Host "$($script:Ver)" -ForegroundColor Green
Write-Host " binary: $InstallDir\catcode.exe" -ForegroundColor Green
Write-Host " web: $webLine" -ForegroundColor Green
if ($script:WithWeb) { Write-Host " expose: $($script:Expose) origin: $($script:ResolvedOrigin)" -ForegroundColor Green }
Write-Host ' --------------------------------------------' -ForegroundColor Green
Write-Host ''
Write-Host ' Open a NEW terminal window (PowerShell, Command Prompt, or Windows Terminal)' -ForegroundColor Green
Write-Host ' so PATH reloads, then run:' -ForegroundColor Green
Write-Host ' catcode' -ForegroundColor Yellow
if ($script:WithWeb) {
Write-Host " web: http://localhost:$Port (logs: $env:LOCALAPPDATA\catalyst-code\catalyst-code-web.log)" -ForegroundColor Green
}
Write-Host ' auth: /login (or set UMANS_API_KEY)'
}
function Summary-Update {
Write-Host ''
Write-Host ' --------------------------------------------' -ForegroundColor Green
Write-Host ' OK Updated Catalyst Code v' -NoNewline -ForegroundColor Green
Write-Host "$($script:Ver)" -ForegroundColor Green
Write-Host ' --------------------------------------------' -ForegroundColor Green
}
function Summary-Uninstall {
Write-Host ''
Write-Host ' --------------------------------------------' -ForegroundColor Green
Write-Host ' OK Removed Catalyst Code' -ForegroundColor Green
Write-Host ' --------------------------------------------' -ForegroundColor Green
Write-Host ' Open a NEW terminal window (PowerShell, CMD, or Windows Terminal) for a clean PATH.' -ForegroundColor DarkGray
}
# -- actions ---------------------------------------------------
function Do-Install {
Write-Host ''
Write-Host ' Catalyst Code - installer (Windows)' -ForegroundColor Cyan
Write-Host ' mode: download (prebuilt, no compile)' -ForegroundColor DarkGray
Resolve-Release
Finalize-WebEnv $script:State
Write-Host " version: $($script:Ver) base: $($script:Base)" -ForegroundColor DarkGray
Write-Host " install: $InstallDir" -ForegroundColor DarkGray
if ($script:WithWeb) { Write-Host " web: $WebDir (port $Port, expose $($script:Expose), origin $($script:ResolvedOrigin))" -ForegroundColor DarkGray }
if ($DryRun) {
W-Info '[dry-run] would download + install catcode.exe'
if ($script:WithWeb) { W-Info '[dry-run] would also install catcode-core.exe + the web service' }
return
}
Install-Tui
if ($script:WithWeb) {
# record the TUI install first so a web failure still leaves a usable state
Save-State $false
Install-CoreForWeb
Install-WebService
Save-State $true
} else {
W-Info 'Skipping web service (pass -WithWeb to install it)'
Save-State $false
}
Summary-Install
}
function Do-Update {
Write-Host ''
Write-Host ' Catalyst Code - update' -ForegroundColor Cyan
$st = Load-State
if (-not $st) { Die "no previous install found at $StateFile - run install.ps1 first." }
$script:State = $st
if ($st.with_web -eq 'yes') { $script:WithWeb = $true }
W-Info "Previous install: v$($st.version) (web: $($st.with_web))"
Resolve-Release
Finalize-WebEnv $st
Write-Host " version: $($script:Ver) base: $($script:Base)" -ForegroundColor DarkGray
if ($DryRun) {
W-Info '[dry-run] would reinstall catcode.exe'
if ($st.with_web -eq 'yes') { W-Info '[dry-run] would reinstall + restart the web service' }
return
}
Install-Tui
if ($st.with_web -eq 'yes') {
$script:WithWeb = $true
Install-CoreForWeb
Install-WebService
Save-State $true
} else {
Save-State $false
}
Summary-Update
}
function Do-Uninstall {
Write-Host ''
Write-Host ' Catalyst Code - uninstall' -ForegroundColor Cyan
$st = Load-State
if ($st) { W-Info "Found previous install (v$($st.version), web: $($st.with_web))" }
else { W-Warn "no state file at $StateFile - attempting default paths" }
if ($DryRun) {
W-Info '[dry-run] would remove the web service + catcode.exe + catcode-core.exe + state'
return
}
# web service first (if it was installed)
$hadWeb = ($st -and $st.with_web -eq 'yes')
if ($hadWeb) {
Uninstall-WebService
}
# binaries
foreach ($b in 'catcode.exe', 'catcode-core.exe') {
$p = Join-Path $InstallDir $b
if (Test-Path -LiteralPath $p) { Remove-Item -LiteralPath $p -Force; W-Ok "Removed $p" }
}
# Drop the install dir from the user PATH (Add-ToPath mirror). MSI installs
# manage PATH via WiX Environment; script installs must clean up themselves.
Remove-FromPath
# state
if (Test-Path -LiteralPath $StateFile) { Remove-Item -LiteralPath $StateFile -Force; W-Ok "Removed $StateFile" }
Summary-Uninstall
}
function Show-Menu {
$st = Load-State
$status = if ($st) { "v$($st.version) (web: $($st.with_web))" } else { 'not installed' }
Write-Host ''
Write-Host ' Catalyst Code - installer menu' -ForegroundColor Cyan
Write-Host " platform: Windows status: $status" -ForegroundColor DarkGray
while ($true) {
Write-Host ''
Write-Host ' What would you like to do?' -ForegroundColor DarkGray
Write-Host ''
Write-Host ' 1 Install (catcode TUI + core)'
Write-Host ' 2 Install with web (TUI + core + 24/7 web service)'
Write-Host ' 3 Add web service (add web to an existing install)'
Write-Host ' 4 Update (download latest + reinstall)'
Write-Host ' 5 Reinstall (reinstall the current version)'
Write-Host ' 6 Uninstall (remove everything)'
Write-Host ' 7 Status (show current install state)'
Write-Host ' 0 Exit'
Write-Host ''
$choice = Read-Host ' Select [0-7]'
if ([string]::IsNullOrWhiteSpace($choice)) { return 'install' } # stdin closed -> default
switch ($choice) {
'1' { return 'install' }
'2' { $script:WithWeb = $true; return 'install' }
'3' { return 'add-web' }
'4' { return 'update' }
'5' { return 'reinstall' }
'6' { return 'uninstall' }
'7' { return 'status' }
'0' { Write-Host ' Bye.' -ForegroundColor DarkGray; return 'exit' }
default { Write-Host ' invalid choice - try again' -ForegroundColor Yellow }
}
}
}
# Interactive settings prompts (menu path only). Enter keeps each default.
# Changing Port / BindHost / WebDir here feeds straight into the NSSM/task
# service install so the web URL updates automatically.
function Prompt-Value {
param([string]$Label, [string]$Default = '')
$hint = if ($Default) { $Default } else { 'empty / latest' }
$ans = Read-Host " $Label [$hint]"
if ([string]::IsNullOrWhiteSpace($ans)) { return $Default }
return $ans.Trim()
}
function Prompt-InstallOptions {
param([string]$Action)
switch ($Action) {
'install' { }
'add-web' { }
'update' { }
'reinstall' { }
default { return }
}
Write-Host ''
$customize = Read-Host ' Customize install settings (paths, port, version)? [y/N]'
if ($customize -notmatch '^(?i)y(es)?$') {
W-Info "Using defaults (install=$InstallDir port=$Port expose=$($script:Expose))"
return
}
Write-Host ''
Write-Host ' Install settings (press Enter to keep each default)' -ForegroundColor Cyan
Write-Host ''
$script:InstallDir = Prompt-Value 'Binary install directory' $InstallDir
$script:Version = Prompt-Value 'Release version pin' $Version
$script:BaseUrl = Prompt-Value 'Download base URL (mirror)' $BaseUrl
$wantWeb = [bool]$script:WithWeb -or ($Action -eq 'add-web')
if (-not $wantWeb -and ($Action -eq 'update' -or $Action -eq 'reinstall')) {
$st = Load-State
if ($st -and $st.with_web -eq 'yes') { $wantWeb = $true }
}
if ($wantWeb) {
$script:WebDir = Prompt-Value 'Web bundle directory' $WebDir
while ($true) {
$raw = Prompt-Value 'Web service port' "$Port"
$p = 0
if ([int]::TryParse($raw, [ref]$p) -and $p -ge 1 -and $p -le 65535) {