-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstart-dev.ps1
More file actions
465 lines (417 loc) · 19.7 KB
/
Copy pathstart-dev.ps1
File metadata and controls
465 lines (417 loc) · 19.7 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
# Run Agency backends and/or frontends with per-agency config.
#
# Usage:
# .\start-dev.ps1 [--clean-run] [--env-file=PATH] <agency> [target]
#
# <agency> One of: npqs, fcau, cda, slpa, customs, sltb, all
# 'all' fans out and starts every agency in parallel.
# [target] One of: all (default), backend, frontend
#
# Flags:
# --clean-run Wipe agency database(s) before starting.
# SQLite: deletes each agency's db.sqlite.path file (from
# its config/<agency>/config.yaml — {agency}_applications.db
# by default).
# Postgres: drops and recreates the database.
# Migrations (go run ./cmd/migrate up) always run before
# the server starts, clean-run or not, so the schema is
# current either way.
# --env-file=PATH Load additional env vars (non-clobbering) before
# --env-file PATH per-agency defaults. Useful for sharing a root .env.
#
# Each agency maps to its own:
# - backend HTTP port and SQLite DB file
# - frontend dev server port
#
# Each agency's backend settings, AND its frontend runtime config/branding
# (IdP client id/scopes, expected OU, logo, portal name, ...) served at
# /config.js, are NOT generated by this script — they're the checked-in
# backend/config/<agency>/config.yaml's web.runtime/web.branding sections (see
# backend/config.example.yaml for the schema). Edit that file directly to
# change an agency's config; this script only picks which one to use
# (CONFIG_PATH) and supplies secrets/DB/CLI settings that stay plain env vars,
# plus each agency's ports.
#
# Env-var precedence for what IS still env-var driven (NSW_CLIENT_SECRET,
# CONFIG_PATH itself, and --clean-run's own DB_DRIVER/DB_HOST/DB_PORT/DB_USER/
# DB_PASSWORD/DB_NAME below):
# parent shell env > --env-file > backend/.env > script defaults
#
# Examples:
# .\start-dev.ps1 npqs # NPQS backend + frontend
# .\start-dev.ps1 fcau backend # FCAU backend only
# .\start-dev.ps1 ird frontend # IRD frontend only
# .\start-dev.ps1 all # every backend + frontend, in parallel
# .\start-dev.ps1 all backend # every backend, no frontends
# .\start-dev.ps1 all --clean-run # wipe all agency DBs, then start
#
# Ctrl-C terminates every child process.
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Orchestration-only per-agency config: BE_PORT, FE_PORT.
# Everything else the frontend needs at runtime (branding, IdP client
# id/OU handle/scopes, ...) lives in backend/config/<agency>/config.yaml's
# web.runtime/web.branding sections instead — the frontend's Vite dev server
# proxies /config.js to its paired backend to read it (see
# frontend/vite.config.ts), same as prod. This table supplies orchestration
# ports for both: the frontend dev server's own port (FE_PORT), and BE_PORT,
# which Start-Frontend also passes through as VITE_API_BASE_URL (the /config.js
# proxy target). BE_PORT/FE_PORT here must match that agency's config.yaml
# (port/allowedOrigins).
# Adding an agency means one line here plus a new config/<agency>/config.yaml.
$AGENCY_CONFIGS = [ordered]@{
npqs = @{ BE_PORT = 8081; FE_PORT = 5174 }
fcau = @{ BE_PORT = 8082; FE_PORT = 5175 }
cda = @{ BE_PORT = 8083; FE_PORT = 5176 }
slpa = @{ BE_PORT = 8084; FE_PORT = 5177 }
customs = @{ BE_PORT = 8085; FE_PORT = 5178 }
sltb = @{ BE_PORT = 8086; FE_PORT = 5179 }
}
$ALL_AGENCIES = @($AGENCY_CONFIGS.Keys | Sort-Object)
function Show-Usage {
$agencies = ($ALL_AGENCIES -join ', ') + ', all'
Write-Host @"
Usage: .\start-dev.ps1 [--clean-run] [--env-file=PATH] <agency> [target]
<agency> One of: $agencies
[target] One of: all (default), backend, frontend
Flags:
--clean-run Wipe agency DB(s) before starting (migrations always run)
--env-file=PATH Load a root-level env file (non-clobbering);
--env-file PATH both forms are supported
Examples:
.\start-dev.ps1 npqs # NPQS backend + frontend
.\start-dev.ps1 fcau backend # FCAU backend only
.\start-dev.ps1 all # every agency, backends + frontends
.\start-dev.ps1 all frontend # every agency, frontends only
.\start-dev.ps1 all --clean-run # wipe all agency DBs, then start
"@ -ForegroundColor Yellow
exit 1
}
# Parse flags and positional args manually to support kebab-case flags
# (PowerShell param() does not allow hyphens in parameter names).
$CLEAN_RUN = $false
$ENV_FILE = ''
$POSITIONAL = [System.Collections.Generic.List[string]]::new()
$i = 0
while ($i -lt $args.Count) {
$arg = $args[$i]
if ($arg -eq '--clean-run') {
$CLEAN_RUN = $true
} elseif ($arg -like '--env-file=*') {
$ENV_FILE = $arg.Substring('--env-file='.Length)
} elseif ($arg -eq '--env-file') {
$i++
if ($i -ge $args.Count -or $args[$i] -like '--*') {
Write-Host "[start-dev] Error: --env-file requires a path value." -ForegroundColor Red
exit 1
}
$ENV_FILE = $args[$i]
} else {
$POSITIONAL.Add($arg)
}
$i++
}
$Agency = if ($POSITIONAL.Count -gt 0) { $POSITIONAL[0] } else { '' }
$Target = if ($POSITIONAL.Count -gt 1) { $POSITIONAL[1] } else { 'all' }
if ($Agency -eq '') { Show-Usage }
if ($Target -notin @('all', 'backend', 'frontend')) {
Write-Host "[start-dev] Unknown target '$Target'." -ForegroundColor Red
Show-Usage
}
if (-not $AGENCY_CONFIGS.Contains($Agency) -and $Agency -ne 'all') {
Write-Host "[start-dev] Unknown agency '$Agency'. Expected: $($ALL_AGENCIES -join ', '), all." -ForegroundColor Red
exit 1
}
$ROOT_DIR = $PSScriptRoot
$BACKEND_DIR = Join-Path $ROOT_DIR 'backend'
$FRONTEND_DIR = Join-Path $ROOT_DIR 'frontend'
# Cross-platform process execution helpers (Windows cmd.exe vs POSIX sh).
$onWindows = ($env:OS -like '*Windows*') -or ($PSVersionTable.Platform -eq 'Win32NT') -or ($IsWindows)
$shellCmd = if ($onWindows) { 'cmd.exe' } else { '/bin/sh' }
$shellArg = if ($onWindows) { '/c' } else { '-c' }
$jobs = [System.Collections.Generic.List[System.Diagnostics.Process]]::new()
function Stop-AllJobs {
if ($jobs.Count -eq 0) { return }
Write-Host ""
Write-Host "[start-dev] Stopping $($jobs.Count) process(es)..."
foreach ($p in $jobs) {
if (-not $p.HasExited) {
try {
if ($onWindows) {
Start-Process taskkill.exe -ArgumentList '/F', '/T', '/PID', $p.Id -NoNewWindow -Wait | Out-Null
} elseif ($PSVersionTable.PSVersion.Major -ge 7) {
$p.Kill($true)
} else {
Start-Process kill -ArgumentList '-TERM', "-$($p.Id)" -NoNewWindow -Wait | Out-Null
}
} catch {
try { $p.Kill() } catch { }
}
}
}
foreach ($p in $jobs) {
try { $p.WaitForExit(3000) | Out-Null } catch { }
}
}
# Source a .env file without clobbering vars already set in the env block.
# Preserves parent-shell overrides (e.g. DB_DRIVER=postgres .\start-dev.ps1 npqs).
function Merge-EnvFile {
param([string]$Path, $Block)
if (-not (Test-Path $Path)) { return }
foreach ($line in Get-Content $Path) {
if ($line -match '^\s*$' -or $line -match '^\s*#') { continue }
if ($line -notmatch '=') { continue }
$cleanLine = $line -replace '^\s*export\s+', ''
$idx = $cleanLine.IndexOf('=')
if ($idx -lt 0) { continue }
$key = $cleanLine.Substring(0, $idx).Trim()
$val = $cleanLine.Substring($idx + 1).Trim()
if ($key -notmatch '^[A-Za-z_][A-Za-z0-9_]*$') { continue }
# Strip surrounding double or single quotes
if ($val -match '^"(.*)"$') {
$val = $Matches[1]
} elseif ($val -match "^'(.*)'$") {
$val = $Matches[1]
}
if (-not $Block.ContainsKey($key)) {
$Block[$key] = $val
}
}
}
# sqlite_path_from_config extracts db.sqlite.path from a config.yaml file (a
# light regex matching this repo's own fixed 2-space/4-space indentation —
# not a full YAML parser, but sufficient for the checked-in
# config/<agency>/config.yaml files this script points CONFIG_PATH at) so
# seeding, cleanup, and logging target the same SQLite file cmd/server and
# cmd/migrate will use, even if a config.yaml is edited to a non-default
# path. Falls back to $Default when the file has no such line (e.g. driver:
# postgres) or can't be read.
function Get-SqlitePathFromConfig {
param(
[string]$ConfigPath,
[string]$Default
)
if (Test-Path $ConfigPath) {
foreach ($line in Get-Content $ConfigPath) {
if ($line -match '^ {4}path:\s*(.*)$') {
$p = $Matches[1].Trim()
if ($p -match '^"(.*)"$' -or $p -match "^'(.*)'$") {
$p = $Matches[1]
}
if ($p -ne '') {
return $p
}
}
}
}
return $Default
}
# ---------------------------------------------------------------------------
# Clean-Databases: wipe agency DB(s) before starting.
# SQLite -> delete each agency's db.sqlite.path file, resolved from its
# config/<agency>/config.yaml (see Get-SqlitePathFromConfig)
# Postgres -> terminate connections, drop, and recreate the database
# ---------------------------------------------------------------------------
function Clean-Databases {
param([string[]]$Agencies)
# Build env: parent shell > --env-file > backend/.env (highest to lowest).
$dbEnv = [System.Environment]::GetEnvironmentVariables('Process').Clone()
if ($ENV_FILE -ne '') { Merge-EnvFile -Path $ENV_FILE -Block $dbEnv }
Merge-EnvFile -Path (Join-Path $BACKEND_DIR '.env') -Block $dbEnv
$dbDriver = if ($dbEnv.ContainsKey('DB_DRIVER')) { $dbEnv['DB_DRIVER'] } else { 'sqlite' }
Write-Host "[start-dev] Cleaning agency databases (driver: $dbDriver)..."
if ($dbDriver -eq 'sqlite') {
foreach ($agency in $Agencies) {
# Resolve CONFIG_PATH the same way Start-Backend/Run-Migrations do
# (relative to BACKEND_DIR, since that's their cwd when they read it).
$agencyConfig = if ($dbEnv.ContainsKey('CONFIG_PATH') -and $dbEnv['CONFIG_PATH']) {
$dbEnv['CONFIG_PATH']
} else {
"config/${agency}/config.yaml"
}
if (-not [System.IO.Path]::IsPathRooted($agencyConfig)) {
$agencyConfig = Join-Path $BACKEND_DIR $agencyConfig
}
$sqlitePath = Get-SqlitePathFromConfig -ConfigPath $agencyConfig -Default "./${agency}_applications.db"
$dbPath = if ([System.IO.Path]::IsPathRooted($sqlitePath)) {
$sqlitePath
} else {
$relPath = $sqlitePath -replace '^\.[/\\]', ''
Join-Path $BACKEND_DIR $relPath
}
if (Test-Path $dbPath) {
Write-Host "[start-dev] Deleting SQLite DB for ${agency}: $dbPath"
Remove-Item $dbPath -Force
} else {
Write-Host "[start-dev] SQLite DB for ${agency} not found (nothing to delete): $dbPath"
}
}
} elseif ($dbDriver -eq 'postgres') {
$psqlCmd = if ($onWindows) { 'psql.exe' } else { 'psql' }
if (-not (Get-Command $psqlCmd -ErrorAction SilentlyContinue)) {
Write-Host "[start-dev] Error: psql required for Postgres DB cleaning but not found in PATH." -ForegroundColor Red
exit 1
}
$dbHost = if ($dbEnv.ContainsKey('DB_HOST')) { $dbEnv['DB_HOST'] } else { 'localhost' }
$dbPort = if ($dbEnv.ContainsKey('DB_PORT')) { $dbEnv['DB_PORT'] } else { '5432' }
$dbUser = if ($dbEnv.ContainsKey('DB_USER')) { $dbEnv['DB_USER'] } else { 'postgres' }
$dbPassword = if ($dbEnv.ContainsKey('DB_PASSWORD')) { $dbEnv['DB_PASSWORD'] } else { 'changeme' }
$dbName = if ($dbEnv.ContainsKey('DB_NAME')) { $dbEnv['DB_NAME'] } else { 'nsw_agency_db' }
# Postgres uses a single shared database; warn if only a subset of agencies
# was selected since this will wipe data for all agencies, not just the chosen ones.
if ($Agencies.Length -lt $ALL_AGENCIES.Length) {
Write-Host "[start-dev] Warning: Postgres uses a shared database ($dbName). --clean-run will wipe data for ALL agencies, not just: $($Agencies -join ' ')." -ForegroundColor Yellow
}
Write-Host "[start-dev] Dropping and recreating Postgres database: $dbName"
$env:PGPASSWORD = $dbPassword
try {
& $psqlCmd -h $dbHost -p $dbPort -U $dbUser -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$dbName' AND pid <> pg_backend_pid();" | Out-Null
& $psqlCmd -h $dbHost -p $dbPort -U $dbUser -d postgres -c "DROP DATABASE IF EXISTS `"$dbName`";"
& $psqlCmd -h $dbHost -p $dbPort -U $dbUser -d postgres -c "CREATE DATABASE `"$dbName`";"
} finally {
Remove-Item Env:PGPASSWORD -ErrorAction SilentlyContinue
}
} else {
Write-Host "[start-dev] Unknown DB_DRIVER '$dbDriver'; skipping database clean." -ForegroundColor Yellow
}
}
# Run-Migrations: apply all pending migrations for each agency DB.
# cmd/migrate reads the same config/<agency>/config.yaml Start-Backend
# points cmd/server at (its db section), so the schema is migrated against
# exactly the DB each backend will connect to. Always called before
# starting backends (after Clean-Databases too, when --clean-run is set)
# since `migrate up` only applies pending migrations and is a no-op on an
# up-to-date schema.
# ---------------------------------------------------------------------------
function Run-Migrations {
param([string[]]$Agencies)
$migrEnv = [System.Environment]::GetEnvironmentVariables('Process').Clone()
if ($ENV_FILE -ne '') { Merge-EnvFile -Path $ENV_FILE -Block $migrEnv }
$dotEnv = Join-Path $BACKEND_DIR '.env'
if (Test-Path $dotEnv) { Merge-EnvFile -Path $dotEnv -Block $migrEnv }
# LoadAndExpand resolves every "{{env:NAME}}" in config.yaml, including
# nsw.clientSecret, even though migrate's own Config struct never reads
# it — so it still needs a default here, same as Start-Backend below.
if (-not $migrEnv.ContainsKey('NSW_CLIENT_SECRET')) {
$migrEnv['NSW_CLIENT_SECRET'] = '1234'
}
Write-Host "[start-dev] Running migrations..."
foreach ($agency in $Agencies) {
$agencyEnv = $migrEnv.Clone()
$configPath = if ($agencyEnv.ContainsKey('CONFIG_PATH') -and $agencyEnv['CONFIG_PATH']) {
$agencyEnv['CONFIG_PATH']
} else {
"config/${agency}/config.yaml"
}
$agencyEnv['CONFIG_PATH'] = $configPath
Write-Host "[start-dev] migrate up -> $configPath"
$psi = [System.Diagnostics.ProcessStartInfo]::new($shellCmd, "$shellArg `"go run ./cmd/migrate up`"")
$psi.WorkingDirectory = $BACKEND_DIR
$psi.UseShellExecute = $false
foreach ($k in $agencyEnv.Keys) { $psi.EnvironmentVariables[$k] = [string]$agencyEnv[$k] }
$proc = [System.Diagnostics.Process]::Start($psi)
$proc.WaitForExit()
if ($proc.ExitCode -ne 0) {
Write-Host "[start-dev] Error: Migration failed for $agency (exit code $($proc.ExitCode))." -ForegroundColor Red
exit $proc.ExitCode
}
}
}
function Start-Backend {
param([string]$AgencyName)
$cfg = $AGENCY_CONFIGS[$AgencyName]
$bePort = $cfg.BE_PORT
$envBlock = [System.Environment]::GetEnvironmentVariables('Process').Clone()
if ($ENV_FILE -ne '') { Merge-EnvFile -Path $ENV_FILE -Block $envBlock }
$dotEnv = Join-Path $BACKEND_DIR '.env'
if (Test-Path $dotEnv) { Merge-EnvFile -Path $dotEnv -Block $envBlock }
if (-not $envBlock.ContainsKey('NSW_CLIENT_SECRET')) {
$envBlock['NSW_CLIENT_SECRET'] = '1234'
}
$configPath = if ($envBlock.ContainsKey('CONFIG_PATH') -and $envBlock['CONFIG_PATH']) {
$envBlock['CONFIG_PATH']
} else {
"config/${AgencyName}/config.yaml"
}
$envBlock['CONFIG_PATH'] = $configPath
$resolvedConfigPath = if (-not [System.IO.Path]::IsPathRooted($configPath)) {
Join-Path $BACKEND_DIR $configPath
} else {
$configPath
}
$dbPath = Get-SqlitePathFromConfig -ConfigPath $resolvedConfigPath -Default "./${AgencyName}_applications.db"
Write-Host "[start-dev] Starting $AgencyName backend -> http://localhost:$bePort (db: $dbPath, config: $configPath)"
$seedFile = Join-Path $BACKEND_DIR "data/seed/${AgencyName}_users.json"
if (Test-Path $seedFile) {
Write-Host "[start-dev] Seeding $AgencyName database using $seedFile..."
$seedPsi = [System.Diagnostics.ProcessStartInfo]::new($shellCmd, "$shellArg `"go run ./cmd/cli user add --file `"$seedFile`"`"")
$seedPsi.WorkingDirectory = $BACKEND_DIR
$seedPsi.UseShellExecute = $false
foreach ($k in $envBlock.Keys) { $seedPsi.EnvironmentVariables[$k] = [string]$envBlock[$k] }
$seedProc = [System.Diagnostics.Process]::Start($seedPsi)
$seedProc.WaitForExit()
}
$psi = [System.Diagnostics.ProcessStartInfo]::new($shellCmd, "$shellArg `"go run ./cmd/server`"")
$psi.WorkingDirectory = $BACKEND_DIR
$psi.UseShellExecute = $false
foreach ($k in $envBlock.Keys) { $psi.EnvironmentVariables[$k] = [string]$envBlock[$k] }
$jobs.Add([System.Diagnostics.Process]::Start($psi))
}
function Start-Frontend {
param([string]$AgencyName)
$cfg = $AGENCY_CONFIGS[$AgencyName]
$fePort = $cfg.FE_PORT
$bePort = $cfg.BE_PORT
Write-Host "[start-dev] Starting $AgencyName frontend -> http://localhost:$fePort (backend: http://localhost:$bePort)"
$envBlock = [System.Environment]::GetEnvironmentVariables('Process').Clone()
if ($ENV_FILE -ne '') { Merge-EnvFile -Path $ENV_FILE -Block $envBlock }
if (-not $envBlock.ContainsKey('VITE_PORT')) {
$envBlock['VITE_PORT'] = "$fePort"
}
if (-not $envBlock.ContainsKey('VITE_API_BASE_URL')) {
$envBlock['VITE_API_BASE_URL'] = "http://localhost:$bePort"
}
$psi = [System.Diagnostics.ProcessStartInfo]::new($shellCmd, "$shellArg `"pnpm run dev`"")
$psi.WorkingDirectory = $FRONTEND_DIR
$psi.UseShellExecute = $false
foreach ($k in $envBlock.Keys) { $psi.EnvironmentVariables[$k] = [string]$envBlock[$k] }
$jobs.Add([System.Diagnostics.Process]::Start($psi))
}
# Load optional root-level env file before per-agency defaults.
if ($ENV_FILE -ne '') {
if (-not (Test-Path $ENV_FILE)) {
Write-Host "[start-dev] Error: --env-file not found: $ENV_FILE" -ForegroundColor Red
exit 1
}
}
# Resolve the agency list to launch.
if ($Agency -eq 'all') {
$agencyList = $ALL_AGENCIES
} else {
$agencyList = @($Agency)
}
if ($CLEAN_RUN) {
Clean-Databases -Agencies $agencyList
}
Run-Migrations -Agencies $agencyList
try {
foreach ($a in $agencyList) {
if ($Target -eq 'all' -or $Target -eq 'backend') { Start-Backend $a }
if ($Target -eq 'all' -or $Target -eq 'frontend') { Start-Frontend $a }
}
Write-Host "[start-dev] $($jobs.Count) process(es) running. Logs from all processes will interleave below. Press Ctrl-C to stop."
# Mirror bash 'wait': keep running until Ctrl-C even if individual processes crash.
# Log exits as they happen but do not kill the remaining processes.
$reported = @{}
while ($true) {
foreach ($p in $jobs) {
if ($p.HasExited -and -not $reported[$p.Id]) {
Write-Host "[start-dev] Process $($p.Id) exited with code $($p.ExitCode)." -ForegroundColor Yellow
$reported[$p.Id] = $true
}
}
Start-Sleep -Milliseconds 500
}
} finally {
Stop-AllJobs
}