-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathsetup.ps1
More file actions
785 lines (674 loc) · 26.8 KB
/
setup.ps1
File metadata and controls
785 lines (674 loc) · 26.8 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
#!/usr/bin/env pwsh
# ----------------------------------------------------------------------------
# Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
#
# WSO2 LLC. licenses this file to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file except
# in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# Check for PowerShell Version Compatibility
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-Host ""
Write-Host "================================================================" -ForegroundColor Red
Write-Host " [ERROR] UNSUPPORTED POWERSHELL VERSION" -ForegroundColor Red
Write-Host "================================================================" -ForegroundColor Red
Write-Host ""
Write-Host " You are currently running PowerShell $($PSVersionTable.PSVersion.ToString())" -ForegroundColor Yellow
Write-Host " Thunder requires PowerShell 7 (Core) or later." -ForegroundColor Yellow
Write-Host ""
Write-Host " Please install the latest version from:"
Write-Host " https://github.com/PowerShell/PowerShell" -ForegroundColor Cyan
Write-Host ""
exit 1
}
# Thunder Setup Script
# Orchestrates the complete setup lifecycle:
# 1. Starts Thunder server with security disabled
# 2. Executes bootstrap scripts (built-in + custom)
# 3. Stops Thunder server
# 4. Exits cleanly
# Exit on any error
$ErrorActionPreference = 'Stop'
# Default settings
$DEBUG_PORT = if ($env:DEBUG_PORT) { [int]$env:DEBUG_PORT } else { 2345 }
$DEBUG_MODE = if ($env:DEBUG_MODE -eq "true") { $true } else { $false }
$BOOTSTRAP_FAIL_FAST = if ($env:BOOTSTRAP_FAIL_FAST -eq "false") { $false } else { $true }
$BOOTSTRAP_SKIP_PATTERN = if ($env:BOOTSTRAP_SKIP_PATTERN) { $env:BOOTSTRAP_SKIP_PATTERN } else { "" }
$BOOTSTRAP_ONLY_PATTERN = if ($env:BOOTSTRAP_ONLY_PATTERN) { $env:BOOTSTRAP_ONLY_PATTERN } else { "" }
$BOOTSTRAP_DIR = if ($env:BOOTSTRAP_DIR) { $env:BOOTSTRAP_DIR } else { ".\bootstrap" }
$WITH_CONSENT = if ($env:WITH_CONSENT -eq 'false') { $false } else { $true }
# ============================================================================
# Logging Functions
# ============================================================================
function Log-Info {
param([string]$Message)
Write-Host "[INFO] $Message" -ForegroundColor Blue
}
function Log-Success {
param([string]$Message)
Write-Host "[SUCCESS] [OK] $Message" -ForegroundColor Green
}
function Log-Warning {
param([string]$Message)
Write-Host "[WARNING] ! $Message" -ForegroundColor Yellow
}
function Log-Error {
param([string]$Message)
Write-Host "[ERROR] X $Message" -ForegroundColor Red
}
function Log-Debug {
param([string]$Message)
if ($env:DEBUG -eq "true") {
Write-Host "[DEBUG] $Message" -ForegroundColor Cyan
}
}
# ============================================================================
# API Call Helper Function
# ============================================================================
function Invoke-ThunderApi {
param(
[string]$Method,
[string]$Endpoint,
[string]$Data = ""
)
# Get base URL from environment variable
$baseUrl = if ($env:THUNDER_API_BASE) {
$env:THUNDER_API_BASE
} else {
Log-Error "THUNDER_API_BASE is not set!"
return @{
StatusCode = 0
Body = ""
Error = "THUNDER_API_BASE not set"
}
}
$url = "$baseUrl$Endpoint"
Log-Debug "API Call: $Method $url"
if ($Data) {
Log-Debug "Request Body: $Data"
}
$responseFile = [System.IO.Path]::GetTempFileName()
$dataFile = $null
try {
$curlArgs = @(
"-X", $Method,
"-k", # Skip SSL verification
"-s", # Silent mode
"-w", "%{http_code}", # Write status code
"-H", "Content-Type: application/json",
"-o", $responseFile # Output to file
)
if ($Data -and ($Method -eq "POST" -or $Method -eq "PUT" -or $Method -eq "PATCH")) {
# Save data to temp file for curl
$dataFile = [System.IO.Path]::GetTempFileName()
if ($PSVersionTable.PSVersion.Major -ge 6) {
$Data | Out-File -FilePath $dataFile -Encoding UTF8NoBOM -NoNewline
} else {
[System.IO.File]::WriteAllText($dataFile, $Data, [System.Text.UTF8Encoding]::new($false))
}
$curlArgs += @("-d", "@$dataFile")
}
$curlArgs += $url
Log-Debug "curl command: curl $($curlArgs -join ' ')"
# Execute curl and capture output
$curlOutput = & curl.exe @curlArgs 2>&1
$curlExitCode = $LASTEXITCODE
# The last line should be the status code
$statusCode = $curlOutput | Select-Object -Last 1
# Handle curl errors (nonzero exit code or status code might be empty or non-numeric)
if ($curlExitCode -ne 0 -or -not $statusCode -or $statusCode -notmatch '^\d+$') {
Log-Error "Failed to execute curl command or received invalid response (exit code: $curlExitCode)"
Log-Error "curl output: $($curlOutput -join "`n")"
return @{
StatusCode = 0
Body = ""
Error = "curl execution failed (exit code: $curlExitCode): $($curlOutput -join '; ')"
}
}
# Read response body (file should always exist, but check defensively)
$body = if (Test-Path $responseFile) {
Get-Content -Path $responseFile -Raw
} else {
""
}
Log-Debug "Response Status: $statusCode"
Log-Debug "Response Body: $body"
$finalBody = if ($body) { $body } else { "" }
return @{
StatusCode = [int]$statusCode
Body = $finalBody
}
}
catch {
Log-Error "API call failed: $_"
Log-Error "Exception: $($_.Exception.Message)"
return @{
StatusCode = 0
Body = ""
Error = $_.Exception.Message
}
}
finally {
# Clean up temp files
if (Test-Path $responseFile) {
Remove-Item $responseFile -Force -ErrorAction SilentlyContinue
}
if ($dataFile -and (Test-Path $dataFile)) {
Remove-Item $dataFile -Force -ErrorAction SilentlyContinue
}
}
}
# ============================================================================
# Help Function
# ============================================================================
function Show-Help {
Write-Host ""
Write-Host "Thunder Setup Script"
Write-Host ""
Write-Host "Usage: .\setup.ps1 [options]"
Write-Host ""
Write-Host "Options:"
Write-Host " --debug Enable debug mode with remote debugging"
Write-Host " --debug-port PORT Set debug port (default: 2345)"
Write-Host " --without-consent Disable the bundled consent server"
Write-Host " --help Show this help message"
Write-Host ""
Write-Host "Description:"
Write-Host " This script performs initial setup by:"
Write-Host " 1. Starting Thunder server temporarily with security disabled"
Write-Host " 2. Running bootstrap scripts to create default resources"
Write-Host " 3. Stopping the server cleanly"
Write-Host ""
Write-Host " After setup completes, use '.\start.ps1' to start Thunder normally."
Write-Host ""
}
# ============================================================================
# Parse Command Line Arguments
# ============================================================================
$i = 0
while ($i -lt $args.Count) {
switch ($args[$i]) {
'--debug' {
$DEBUG_MODE = $true
$i++
break
}
'--debug-port' {
$i++
if ($i -lt $args.Count) {
$DEBUG_PORT = [int]$args[$i]
$i++
}
else {
Write-Host "Missing value for --debug-port" -ForegroundColor Red
exit 1
}
break
}
'--without-consent' {
$WITH_CONSENT = $false
$i++
break
}
'--help' {
Show-Help
exit 0
}
default {
Write-Host "Unknown option: $($args[$i])" -ForegroundColor Red
Write-Host "Use --help for usage information"
exit 1
}
}
}
# ============================================================================
# Read Configuration from deployment.yaml
# ============================================================================
$CONFIG_FILE = ".\repository\conf\deployment.yaml"
function Read-Config {
$configFile = $CONFIG_FILE
if (-not (Test-Path $configFile)) {
# Try alternative path (for packaged distribution)
$configFile = ".\backend\cmd\server\repository\conf\deployment.yaml"
}
if (-not (Test-Path $configFile)) {
Log-Warning "Configuration file not found, using defaults"
return $false
}
Log-Debug "Reading configuration from: $configFile"
# Try yq first (YAML parser)
if (Get-Command yq -ErrorAction SilentlyContinue) {
$script:HOSTNAME = & yq eval '.server.hostname // "localhost"' $configFile 2>$null
$script:PORT = & yq eval '.server.port // 8090' $configFile 2>$null
$script:HTTP_ONLY = & yq eval '.server.http_only // false' $configFile 2>$null
$script:PUBLIC_URL = & yq eval '.server.public_url // ""' $configFile 2>$null
}
else {
# Fallback: basic parsing with Select-String
$content = Get-Content $configFile -Raw
# Parse hostname
if ($content -match '(?m)^\s*hostname:\s*[''"]?([^''"\s]+)[''"]?') {
$script:HOSTNAME = $matches[1]
}
else {
$script:HOSTNAME = "localhost"
}
# Parse port
if ($content -match '(?m)^\s*port:\s*(\d+)') {
$script:PORT = [int]$matches[1]
}
else {
$script:PORT = 8090
}
# Parse http_only
if ($content -match '(?m)http_only:\s*true') {
$script:HTTP_ONLY = "true"
}
else {
$script:HTTP_ONLY = "false"
}
# Parse public_url (quoted or unquoted)
if ($content -match '(?m)^\s*public_url:\s*[''"]([^''"]+)[''"]') {
$script:PUBLIC_URL = $matches[1]
}
elseif ($content -match '(?m)^\s*public_url:\s*([^\s#]+)') {
$script:PUBLIC_URL = $matches[1]
}
else {
$script:PUBLIC_URL = ""
}
}
# Determine protocol
if ($script:HTTP_ONLY -eq "true") {
$script:PROTOCOL = "http"
}
else {
$script:PROTOCOL = "https"
}
return $true
}
# Read configuration
Read-Config | Out-Null
# Construct base URL (internal API endpoint)
$BASE_URL = "$($script:PROTOCOL)://$($script:HOSTNAME):$($script:PORT)"
$script:THUNDER_API_BASE = $BASE_URL
# Construct public URL (external/redirect URLs), strip trailing slash to avoid double slashes in paths
$PUBLIC_URL = if ($script:PUBLIC_URL) { $script:PUBLIC_URL.TrimEnd('/') } else { $BASE_URL }
# Export environment variables for bootstrap scripts
$env:THUNDER_API_BASE = $BASE_URL
$env:THUNDER_PUBLIC_URL = $PUBLIC_URL
Write-Host ""
Write-Host "========================================="
Write-Host " Thunder Setup"
Write-Host "========================================="
Write-Host ""
Write-Host "Server URL: $BASE_URL" -ForegroundColor Blue
Write-Host "Public URL: $PUBLIC_URL" -ForegroundColor Blue
if ($DEBUG_MODE) {
Write-Host "Debug: Enabled (port $DEBUG_PORT)" -ForegroundColor Blue
}
Write-Host ""
# Log PowerShell version for debugging
Log-Debug "PowerShell Version: $($PSVersionTable.PSVersion)"
Log-Debug "PowerShell Edition: $($PSVersionTable.PSEdition)"
Log-Debug "OS: $($PSVersionTable.OS)"
Log-Debug "Platform: $($PSVersionTable.Platform)"
# ============================================================================
# Kill Existing Processes on Ports
# ============================================================================
function Stop-PortListener {
param([int]$port)
Write-Host "Checking for processes listening on TCP port $port..."
try {
$pids = Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction Stop |
Select-Object -ExpandProperty OwningProcess -Unique
}
catch {
# Fallback to netstat parsing
$pids = @()
try {
$netstat = & netstat -ano 2>$null | Select-String ":$port"
foreach ($line in $netstat) {
$parts = ($line -split '\s+') | Where-Object { $_ -ne '' }
if ($parts.Count -ge 5) {
$procId = $parts[-1]
if ([int]::TryParse($procId, [ref]$null)) {
$pids += [int]$procId
}
}
}
}
catch { }
}
$pids = $pids | Where-Object { $_ -and ($_ -ne 0) } | Select-Object -Unique
foreach ($procId in $pids) {
try {
Write-Host "Killing PID $procId that is listening on port $port"
Stop-Process -Id $procId -Force -ErrorAction SilentlyContinue
}
catch {
Write-Host "Unable to kill PID $procId : $_" -ForegroundColor Yellow
}
}
}
if ($DEBUG_MODE) {
Stop-PortListener -port $DEBUG_PORT
}
Start-Sleep -Seconds 1
# Check for Delve if debug mode is enabled
if ($DEBUG_MODE -and -not (Get-Command dlv -ErrorAction SilentlyContinue)) {
Write-Host "[ERROR] Debug mode requires Delve debugger" -ForegroundColor Red
Write-Host ""
Write-Host "[INFO] Install Delve using:" -ForegroundColor Cyan
Write-Host " go install github.com/go-delve/delve/cmd/dlv@latest" -ForegroundColor Cyan
exit 1
}
# ============================================================================
# Start Thunder Server with Security Disabled
# ============================================================================
Write-Host "[WARN] Starting temporary server with security disabled..." -ForegroundColor Yellow
Write-Host ""
# Export environment variable to skip security
$hadSkipSecurity = Test-Path Env:THUNDER_SKIP_SECURITY
$previousSkipSecurity = $env:THUNDER_SKIP_SECURITY
$env:THUNDER_SKIP_SECURITY = "true"
# Resolve thunder executable path
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$possible = @(
(Join-Path $scriptDir 'thunder.exe'),
(Join-Path $scriptDir 'thunder')
)
$thunderPath = $possible | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $thunderPath) {
$thunderPath = Join-Path $scriptDir 'thunder'
}
# Start Consent Server (if enabled)
$consentProc = $null
$consentDir = Join-Path $scriptDir 'consent'
if ($WITH_CONSENT) {
if (-not (Test-Path $consentDir)) {
Log-Error "Consent server is enabled but consent directory not found: $consentDir"
exit 1
}
Write-Host "[INFO] Starting Consent Server..." -ForegroundColor Cyan
$consentPort = if ($env:CONSENT_SERVER_PORT) { $env:CONSENT_SERVER_PORT } else { "9090" }
$consentBinary = @(
(Join-Path $consentDir 'consent-server.exe'),
(Join-Path $consentDir 'consent-server')
) | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $consentBinary) {
Log-Error "Consent server is enabled but consent-server binary not found in: $consentDir"
exit 1
}
$consentProc = Start-Process -FilePath $consentBinary -WorkingDirectory $consentDir -NoNewWindow -PassThru
$consentTimeout = 30
$consentElapsed = 0
while ($consentElapsed -lt $consentTimeout) {
if ($consentProc.HasExited) {
Log-Error "Consent server process exited unexpectedly (code $($consentProc.ExitCode))"
exit 1
}
try {
$resp = Invoke-WebRequest -Uri "http://localhost:${consentPort}/health/readiness" -UseBasicParsing -ErrorAction Stop
if ($resp.StatusCode -eq 200) {
Write-Host "[INFO] Consent server is ready" -ForegroundColor Cyan
break
}
} catch { }
Start-Sleep -Seconds 1
$consentElapsed++
}
if ($consentElapsed -ge $consentTimeout) {
Log-Error "Consent server failed to become ready within ${consentTimeout}s"
exit 1
}
}
$proc = $null
try {
if ($DEBUG_MODE) {
$dlvArgs = @(
'exec'
"--listen=:$DEBUG_PORT"
'--headless=true'
'--api-version=2'
'--accept-multiclient'
'--continue'
$thunderPath
)
$proc = Start-Process -FilePath dlv -ArgumentList $dlvArgs -WorkingDirectory $scriptDir -NoNewWindow -PassThru
}
else {
$proc = Start-Process -FilePath $thunderPath -WorkingDirectory $scriptDir -NoNewWindow -PassThru
}
$THUNDER_PID = $proc.Id
# Cleanup function
$cleanup = {
Write-Host ""
Write-Host "[STOP] Stopping temporary server..." -ForegroundColor Cyan
if ($proc -and -not $proc.HasExited) {
try {
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
} catch { }
}
if ($consentProc -and -not $consentProc.HasExited) {
try {
Stop-Process -Id $consentProc.Id -Force -ErrorAction SilentlyContinue
} catch { }
}
}
# Register cleanup on exit
Register-EngineEvent PowerShell.Exiting -Action $cleanup | Out-Null
# ============================================================================
# Wait for Server to be Ready
# ============================================================================
Write-Host "[WAIT] Waiting for server to be ready..." -ForegroundColor Blue
Write-Host " Server URL: $BASE_URL" -ForegroundColor Blue
$TIMEOUT = 60
$ELAPSED = 0
$RETRY_DELAY = 2
$lastError = ""
while ($ELAPSED -lt $TIMEOUT) {
Log-Debug "Attempting health check (attempt $([math]::Floor($ELAPSED / $RETRY_DELAY) + 1))..."
$healthUrl = "$BASE_URL/health/readiness"
Log-Debug "Making request to: $healthUrl"
$requestStart = Get-Date
$statusCode = & curl.exe -k -s -w "%{http_code}" -o NUL $healthUrl 2>&1 | Select-Object -Last 1
$requestDuration = (Get-Date) - $requestStart
Log-Debug "Request completed in $([math]::Round($requestDuration.TotalSeconds, 2))s with status: $statusCode"
if ($statusCode -eq "200") {
Write-Host ""
Write-Host "[OK] Server is ready" -ForegroundColor Green
Log-Debug "Health check response: $body"
Write-Host ""
break
}
else {
# Server not ready yet
$currentError = "HTTP $statusCode"
# Log additional details when error status changes
if ($currentError -ne $lastError) {
Write-Host ""
Log-Debug "Health check failed with status: $statusCode"
if (-not $statusCode -or $statusCode -eq '000') {
Log-Debug "Connection refused - server not yet listening"
} elseif ($statusCode -match "^50[0-9]$") {
Log-Debug "Server error - server might be starting"
}
$lastError = $currentError
Write-Host "." -NoNewline
} else {
Write-Host "." -NoNewline
}
}
Start-Sleep -Seconds $RETRY_DELAY
$ELAPSED += $RETRY_DELAY
}
if ($ELAPSED -ge $TIMEOUT) {
Write-Host ""
Write-Host "[ERROR] Server health check failed within $TIMEOUT seconds" -ForegroundColor Red
Write-Host "Expected server at: $BASE_URL" -ForegroundColor Red
Write-Host "Last status: $lastError" -ForegroundColor Red
exit 1
}
# ============================================================================
# Run Bootstrap Scripts
# ============================================================================
# Check if bootstrap directory exists
if (-not (Test-Path $BOOTSTRAP_DIR)) {
Log-Warning "Bootstrap directory not found: $BOOTSTRAP_DIR"
Log-Info "Skipping bootstrap execution"
}
else {
Log-Info "========================================="
Log-Info "Thunder Bootstrap Process"
Log-Info "========================================="
Log-Info "Bootstrap directory: $BOOTSTRAP_DIR"
Log-Info "Fail fast: $BOOTSTRAP_FAIL_FAST"
Log-Info "Started at: $(Get-Date)"
Write-Host ""
# Collect all PowerShell scripts from bootstrap directory
$scripts = @()
# Find PowerShell scripts in bootstrap directory
if (Test-Path $BOOTSTRAP_DIR) {
Log-Debug "Scanning $BOOTSTRAP_DIR for PowerShell scripts..."
$scripts = Get-ChildItem -Path $BOOTSTRAP_DIR -Filter "*.ps1" -File -ErrorAction SilentlyContinue
Log-Debug "Found $($scripts.Count) PowerShell script(s)"
foreach ($bootstrapScript in $scripts) {
Log-Debug " - $($bootstrapScript.Name)"
}
}
# Sort scripts by filename (numeric prefix determines order)
$sortedScripts = $scripts | Sort-Object Name
if ($sortedScripts.Count -eq 0) {
Log-Warning "No bootstrap scripts found"
}
else {
Log-Info "Discovered $($sortedScripts.Count) PowerShell script(s)"
Log-Debug "Scripts will be executed in this order:"
foreach ($bootstrapScript in $sortedScripts) {
Log-Debug " - $($bootstrapScript.Name)"
}
Write-Host ""
# Execute scripts
$scriptCount = 0
$successCount = 0
$failedCount = 0
$skippedCount = 0
foreach ($bootstrapScript in $sortedScripts) {
$scriptName = $bootstrapScript.Name
# Skip if matches skip pattern
if ($BOOTSTRAP_SKIP_PATTERN -and ($scriptName -match $BOOTSTRAP_SKIP_PATTERN)) {
Log-Info "[SKIP] Skipping $scriptName (matches skip pattern regex: $BOOTSTRAP_SKIP_PATTERN)"
$skippedCount++
continue
}
# Skip if doesn't match only pattern
if ($BOOTSTRAP_ONLY_PATTERN -and ($scriptName -notmatch $BOOTSTRAP_ONLY_PATTERN)) {
Log-Info "[SKIP] Skipping $scriptName (doesn't match only pattern: $BOOTSTRAP_ONLY_PATTERN)"
$skippedCount++
continue
}
Log-Info "[EXEC] Executing: $scriptName"
$scriptCount++
# Execute PowerShell script
$startTime = Get-Date
try {
& $bootstrapScript.FullName
$exitCode = $LASTEXITCODE
$endTime = Get-Date
$duration = [math]::Round(($endTime - $startTime).TotalSeconds, 2)
if ($exitCode -eq 0 -or $null -eq $exitCode) {
Log-Success "$scriptName completed (${duration}s)"
$successCount++
}
else {
Log-Error "$scriptName failed with exit code $exitCode (${duration}s)"
$failedCount++
if ($BOOTSTRAP_FAIL_FAST) {
Log-Error "Stopping bootstrap (BOOTSTRAP_FAIL_FAST=true)"
exit 1
}
}
}
catch {
$endTime = Get-Date
$duration = [math]::Round(($endTime - $startTime).TotalSeconds, 2)
Log-Error "$scriptName failed with error: $_ (${duration}s)"
$failedCount++
if ($BOOTSTRAP_FAIL_FAST) {
Log-Error "Stopping bootstrap (BOOTSTRAP_FAIL_FAST=true)"
exit 1
}
}
Write-Host ""
}
# Summary
Write-Host ""
Log-Info "========================================="
Log-Info "Bootstrap Summary"
Log-Info "========================================="
Log-Info "Total scripts discovered: $($sortedScripts.Count)"
Log-Info "Executed: $scriptCount"
Log-Success "Successful: $successCount"
if ($failedCount -gt 0) {
Log-Error "Failed: $failedCount"
}
if ($skippedCount -gt 0) {
Log-Info "Skipped: $skippedCount"
}
Log-Info "Completed at: $(Get-Date)"
Log-Info "========================================="
if ($failedCount -gt 0) {
exit 1
}
Log-Success "Bootstrap completed successfully!"
}
}
# ============================================================================
# Setup Completed
# ============================================================================
Write-Host ""
Write-Host "========================================="
Write-Host "[OK] Setup completed successfully!" -ForegroundColor Green
Write-Host "========================================="
Write-Host ""
Write-Host "[INFO] Next steps:"
Write-Host " 1. Start the server: .\start.ps1" -ForegroundColor Cyan
Write-Host " 2. Access Thunder at: $BASE_URL" -ForegroundColor Cyan
Write-Host " 3. Login with admin credentials:"
Write-Host " Username: admin" -ForegroundColor Cyan
Write-Host " Password: admin" -ForegroundColor Cyan
Write-Host ""
}
finally {
# Cleanup
Write-Host ""
Write-Host "[STOP] Stopping temporary server..." -ForegroundColor Cyan
if ($proc -and -not $proc.HasExited) {
try {
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
} catch { }
}
if ($consentProc -and -not $consentProc.HasExited) {
try {
Stop-Process -Id $consentProc.Id -Force -ErrorAction SilentlyContinue
} catch { }
}
# Restore THUNDER_SKIP_SECURITY to its previous state
if (-not $hadSkipSecurity) {
Remove-Item Env:THUNDER_SKIP_SECURITY -ErrorAction SilentlyContinue
} else {
$env:THUNDER_SKIP_SECURITY = $previousSkipSecurity
}
}
exit 0