-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.ps1
More file actions
1400 lines (1111 loc) · 46.3 KB
/
build.ps1
File metadata and controls
1400 lines (1111 loc) · 46.3 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
Builds the StartSet project with enterprise code signing and MSI/NuGet packaging.
.DESCRIPTION
This script automates the build and packaging process for StartSet,
including building .NET binaries, signing them with enterprise certificates, and creating MSI installers.
DEFAULT BEHAVIOR: Running .\build.ps1 with no parameters builds everything (binaries + MSI + NUPKG) with signing.
Version Format: YYYY.MM.DD.HHMM (e.g., 2025.12.15.1430)
MSI versions are automatically converted to compatible format (YY.MM.DDHH).
.PARAMETER Sign
Sign binaries with code signing certificate (default if enterprise cert found)
.PARAMETER NoSign
Skip code signing (for development only)
.PARAMETER Thumbprint
Use specific certificate thumbprint for signing
.PARAMETER Binaries
Build all binaries only (skip packaging)
.PARAMETER Install
Install MSI package after building (requires elevation)
.PARAMETER IntuneWin
Create IntuneWin packages for Intune deployment
.PARAMETER Dev
Development mode - stops services, faster iteration, skips signing
.PARAMETER SignMSI
Sign existing MSI files in release directory (standalone operation)
.PARAMETER SkipMSI
Skip MSI packaging, build only .nupkg packages
.PARAMETER PackageOnly
Package existing binaries only (skip build), create both MSI and NUPKG
.PARAMETER NupkgOnly
Create .nupkg packages only using existing binaries (skip build and MSI)
.PARAMETER MsiOnly
Create MSI packages only using existing binaries (skip build and NUPKG)
.PARAMETER PkgOnly
Create .pkg packages only using existing binaries (direct binary payload)
.PARAMETER Clean
Clean all build artifacts before building
.PARAMETER Configuration
Build configuration (Debug or Release). Default: Release
.PARAMETER Architecture
Target architecture (x64, arm64, or both). Default: both
.PARAMETER Test
Run tests after building
.EXAMPLE
.\build.ps1
# Full build with auto-signing (binaries + MSI + NUPKG)
.EXAMPLE
.\build.ps1 -Dev -Install
# Development mode: fast rebuild and install
.EXAMPLE
.\build.ps1 -Binaries
# Build only binaries, skip packaging
.EXAMPLE
.\build.ps1 -Sign -Thumbprint XX
# Force sign with specific certificate
.EXAMPLE
.\build.ps1 -SkipMSI
# Build only .nupkg packages, skip MSI packaging
.EXAMPLE
.\build.ps1 -PackageOnly
# Package existing binaries (both MSI and NUPKG)
.EXAMPLE
.\build.ps1 -NupkgOnly
# Create only .nupkg packages from existing binaries
.EXAMPLE
.\build.ps1 -MsiOnly
# Create only MSI packages from existing binaries
.EXAMPLE
.\build.ps1 -PkgOnly
# Create only .pkg packages from existing binaries
.EXAMPLE
.\build.ps1 -IntuneWin
# Full build including .intunewin packages
.EXAMPLE
.\build.ps1 -SignMSI
# Sign existing MSI files in release directory
#>
[CmdletBinding()]
param(
[switch]$Sign,
[switch]$NoSign,
[string]$Thumbprint,
[switch]$Binaries,
[switch]$Install,
[switch]$IntuneWin,
[switch]$Dev,
[switch]$SignMSI,
[switch]$SkipMSI,
[switch]$PackageOnly,
[switch]$NupkgOnly,
[switch]$MsiOnly,
[switch]$PkgOnly,
[switch]$Clean,
[switch]$Test,
[ValidateSet('Debug', 'Release')]
[string]$Configuration = 'Release',
[ValidateSet('x64', 'arm64', 'both')]
[string]$Architecture = 'both'
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
#region Logging Functions
function Write-BuildLog {
param(
[string]$Message,
[ValidateSet("INFO", "WARNING", "ERROR", "SUCCESS")]
[string]$Level = "INFO"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$color = switch ($Level) {
"INFO" { "Cyan" }
"WARNING" { "Yellow" }
"ERROR" { "Red" }
"SUCCESS" { "Green" }
}
Write-Host "[$timestamp] " -NoNewline -ForegroundColor DarkGray
Write-Host "[$Level] " -NoNewline -ForegroundColor $color
Write-Host $Message
}
#endregion
# Load environment variables from .env file if it exists
function Import-DotEnv {
param([string]$Path = ".env")
if (Test-Path $Path) {
Write-BuildLog "Loading environment variables from $Path"
Get-Content $Path | ForEach-Object {
if ($_ -match '^\s*([^#][^=]*)\s*=\s*(.*)\s*$') {
$name = $matches[1].Trim()
$value = $matches[2].Trim()
if ($value -match '^"(.*)"$' -or $value -match "^'(.*)'$") {
$value = $matches[1]
}
[Environment]::SetEnvironmentVariable($name, $value, [EnvironmentVariableTarget]::Process)
}
}
}
}
Import-DotEnv
# Enterprise certificate configuration - loaded from environment or .env file
$Global:EnterpriseCertCN = $env:STARTSET_CERT_CN ?? $env:CIMIAN_CERT_CN ?? 'EmilyCarrU Intune Windows Enterprise Certificate'
$Global:EnterpriseCertSubject = $env:STARTSET_CERT_SUBJECT ?? $env:CIMIAN_CERT_SUBJECT ?? 'EmilyCarrU'
# Script constants
$script:RootDir = $PSScriptRoot
$script:OutputDir = Join-Path $RootDir 'release'
$script:BuildDir = Join-Path $RootDir 'build'
$script:SrcDir = Join-Path $RootDir 'src'
#region Certificate and Signing Functions
function Test-Command {
param ([string]$Command)
return $null -ne (Get-Command $Command -ErrorAction SilentlyContinue)
}
function Test-CimiPkg {
$c = Get-Command cimipkg.exe -ErrorAction SilentlyContinue
if ($c) { return $true }
# Check in common locations
$possiblePaths = @(
"$PSScriptRoot\..\CimianToolsGo\release\x64\cimipkg.exe",
"$PSScriptRoot\..\..\packages\CimianToolsGo\release\x64\cimipkg.exe",
"C:\Program Files\Cimian\cimipkg.exe"
)
foreach ($path in $possiblePaths) {
if (Test-Path $path) {
return $true
}
}
return $false
}
function Get-CimiPkgPath {
$c = Get-Command cimipkg.exe -ErrorAction SilentlyContinue
if ($c) { return $c.Source }
# Check in common locations
$possiblePaths = @(
"$PSScriptRoot\..\CimianToolsGo\release\x64\cimipkg.exe",
"$PSScriptRoot\..\..\packages\CimianToolsGo\release\x64\cimipkg.exe",
"C:\Program Files\Cimian\cimipkg.exe"
)
foreach ($path in $possiblePaths) {
if (Test-Path $path) {
return $path
}
}
throw "cimipkg.exe not found. Build CimianToolsGo first or add cimipkg to PATH."
}
function Get-SigningCertThumbprint {
[OutputType([hashtable])]
param([string]$ProvidedThumbprint)
# Use provided thumbprint first
if ($ProvidedThumbprint) {
$cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object { $_.Thumbprint -eq $ProvidedThumbprint }
if ($cert) {
return @{ Thumbprint = $cert.Thumbprint; Store = "CurrentUser"; Certificate = $cert }
}
$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Thumbprint -eq $ProvidedThumbprint }
if ($cert) {
return @{ Thumbprint = $cert.Thumbprint; Store = "LocalMachine"; Certificate = $cert }
}
}
# Check CurrentUser store first
$cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object {
$_.HasPrivateKey -and $_.Subject -like "*$Global:EnterpriseCertSubject*"
} | Sort-Object NotAfter -Descending | Select-Object -First 1
if ($cert) {
return @{ Thumbprint = $cert.Thumbprint; Store = "CurrentUser"; Certificate = $cert }
}
# Check LocalMachine store
$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object {
$_.HasPrivateKey -and $_.Subject -like "*$Global:EnterpriseCertSubject*"
} | Sort-Object NotAfter -Descending | Select-Object -First 1
if ($cert) {
return @{ Thumbprint = $cert.Thumbprint; Store = "LocalMachine"; Certificate = $cert }
}
return $null
}
$Global:SignToolPath = $null
function Get-SignToolPath {
if ($Global:SignToolPath -and (Test-Path $Global:SignToolPath)) {
return $Global:SignToolPath
}
# Check PATH (prefer x64)
$c = Get-Command signtool.exe -ErrorAction SilentlyContinue
if ($c -and $c.Source -match '\\x64\\') {
$Global:SignToolPath = $c.Source
return $Global:SignToolPath
}
# Search Windows SDK
$programFilesx86 = [Environment]::GetFolderPath('ProgramFilesX86')
$searchRoot = Join-Path $programFilesx86 "Windows Kits\10\bin"
if (Test-Path $searchRoot) {
$candidates = Get-ChildItem -Path $searchRoot -Recurse -Filter "signtool.exe" -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -match '\\x64\\' } |
Sort-Object { $_.Directory.Parent.Name } -Descending
if ($candidates -and $candidates.Count -gt 0) {
$Global:SignToolPath = $candidates[0].FullName
return $Global:SignToolPath
}
}
# Check registry
try {
$kitsRoot = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows Kits\Installed Roots" -Name KitsRoot10 -ErrorAction SilentlyContinue
if ($kitsRoot) {
$regRoot = Join-Path $kitsRoot.KitsRoot10 'bin'
if (Test-Path $regRoot) {
$candidates = Get-ChildItem -Path $regRoot -Recurse -Filter "signtool.exe" -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -match '\\x64\\' } |
Sort-Object { $_.Directory.Parent.Name } -Descending
if ($candidates -and $candidates.Count -gt 0) {
$Global:SignToolPath = $candidates[0].FullName
return $Global:SignToolPath
}
}
}
} catch {}
return $null
}
function Test-SignTool {
$path = Get-SignToolPath
if (-not $path) {
throw "signtool.exe not found. Install Windows 10/11 SDK (Signing Tools)."
}
}
function Invoke-SignArtifact {
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$Thumbprint,
[string]$Store = "CurrentUser",
[int]$MaxAttempts = 4
)
if (-not (Test-Path -LiteralPath $Path)) {
throw "File not found: $Path"
}
$signToolExe = Get-SignToolPath
if (-not $signToolExe) {
throw "signtool.exe not found. Install Windows 10/11 SDK."
}
$storeParam = if ($Store -eq "CurrentUser") { "/s", "My" } else { "/s", "My", "/sm" }
$tsas = @(
'http://timestamp.digicert.com',
'http://timestamp.sectigo.com',
'http://timestamp.entrust.net/TSS/RFC3161sha2TS'
)
$attempt = 0
while ($attempt -lt $MaxAttempts) {
$attempt++
foreach ($tsa in $tsas) {
try {
Write-BuildLog "Signing (attempt $attempt): $Path" "INFO"
$signArgs = @(
"sign"
"/sha1", $Thumbprint
"/tr", $tsa
"/td", "sha256"
"/fd", "sha256"
) + $storeParam + @($Path)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $signToolExe
$psi.Arguments = $signArgs -join ' '
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
$process = [System.Diagnostics.Process]::Start($psi)
$null = $process.StandardOutput.ReadToEnd()
$null = $process.StandardError.ReadToEnd()
$process.WaitForExit()
if ($process.ExitCode -eq 0) {
Write-BuildLog "Successfully signed: $Path" "SUCCESS"
return
}
}
catch {
Write-BuildLog "Signing attempt failed: $_" "WARNING"
}
Start-Sleep -Seconds (2 * $attempt)
}
}
throw "Signing failed after $MaxAttempts attempts: $Path"
}
function Invoke-SignNuget {
param(
[Parameter(Mandatory)][string]$NupkgPath,
[string]$Thumbprint
)
if (-not (Test-Path $NupkgPath)) {
throw "NuGet package '$NupkgPath' not found."
}
if (-not $Thumbprint) {
$certInfo = Get-SigningCertThumbprint
$Thumbprint = if ($certInfo) { $certInfo.Thumbprint } else { $null }
}
if (-not $Thumbprint) {
Write-BuildLog "No enterprise code-signing cert present - skipping NuGet signing." "WARNING"
return $false
}
$tsa = 'http://timestamp.digicert.com'
& nuget.exe sign $NupkgPath `
-CertificateStoreName My `
-CertificateSubjectName $Global:EnterpriseCertCN `
-Timestamper $tsa
if ($LASTEXITCODE) {
Write-BuildLog "nuget sign failed ($LASTEXITCODE) for '$NupkgPath'" "WARNING"
return $false
}
Write-BuildLog "NuGet package signed: $NupkgPath" "SUCCESS"
return $true
}
#endregion
#region Version Functions
function Get-BuildVersion {
$currentTime = Get-Date
$fullVersion = $currentTime.ToString("yyyy.MM.dd.HHmm")
$semanticVersion = "{0}.{1}.{2}.{3}" -f ($currentTime.Year - 2000), $currentTime.Month, $currentTime.Day, $currentTime.ToString("HHmm")
return @{
Full = $fullVersion
Semantic = $semanticVersion
MsiCompatible = "{0}.{1}.{2}{3:D2}" -f ($currentTime.Year - 2000), $currentTime.Month, $currentTime.Day, [int]$currentTime.ToString("HH")
}
}
#endregion
#region Build Functions
function Initialize-BuildEnvironment {
Write-BuildLog "Initializing build environment..."
# Create output directories
$archs = if ($Architecture -eq 'both') { @('x64', 'arm64') } elseif ($Architecture -eq 'x64') { @('x64') } else { @('arm64') }
foreach ($arch in $archs) {
$archDir = Join-Path $OutputDir $arch
if (-not (Test-Path $archDir)) {
New-Item -ItemType Directory -Path $archDir -Force | Out-Null
}
}
# Verify dotnet is available
if (-not (Test-Command "dotnet")) {
throw ".NET SDK not found. Please install .NET SDK."
}
$dotnetVersion = & dotnet --version
Write-BuildLog "Using .NET SDK: $dotnetVersion" "SUCCESS"
}
function Invoke-Clean {
Write-BuildLog "Cleaning build artifacts..."
# Clean release directory
if (Test-Path $OutputDir) {
Remove-Item -Path "$OutputDir\*" -Recurse -Force -ErrorAction SilentlyContinue
}
# Clean bin/obj folders in projects
Get-ChildItem -Path $SrcDir -Include 'bin', 'obj' -Recurse -Directory | ForEach-Object {
Remove-Item -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue
}
Write-BuildLog "Clean complete" -Level 'SUCCESS'
}
function Build-Solution {
Write-BuildLog "Building solution..."
$solutionPath = Join-Path $RootDir 'StartSet.sln'
$config = if ($Dev) { 'Debug' } else { $Configuration }
$buildArgs = @(
'build',
$solutionPath,
'--configuration', $config,
'--verbosity', 'minimal'
)
Write-BuildLog "dotnet $($buildArgs -join ' ')"
& dotnet @buildArgs
if ($LASTEXITCODE -ne 0) {
throw "Solution build failed with exit code $LASTEXITCODE"
}
Write-BuildLog "Solution build complete" -Level 'SUCCESS'
}
function Publish-Binary {
param(
[string]$Name,
[string]$ProjectPath,
[string]$RuntimeIdentifier,
[string]$OutputPath,
[hashtable]$Version
)
$config = if ($Dev) { 'Debug' } else { $Configuration }
$publishArgs = @(
'publish',
$ProjectPath,
'--configuration', $config,
'--runtime', $RuntimeIdentifier,
'--self-contained', 'true',
'--output', $OutputPath,
'-p:PublishSingleFile=true',
'-p:PublishReadyToRun=true',
'-p:EnableCompressionInSingleFile=true',
'-p:IncludeNativeLibrariesForSelfExtract=true',
"-p:Version=$($Version.Full)",
'--verbosity', 'minimal'
)
Write-BuildLog "Publishing $Name for $RuntimeIdentifier..."
& dotnet @publishArgs
if ($LASTEXITCODE -ne 0) {
throw "Failed to publish $Name for $RuntimeIdentifier"
}
Write-BuildLog "$Name ($RuntimeIdentifier) built successfully" -Level 'SUCCESS'
}
function Build-AllBinaries {
param([hashtable]$Version)
$archs = if ($Architecture -eq 'both') { @('x64', 'arm64') } elseif ($Architecture -eq 'x64') { @('x64') } else { @('arm64') }
$runtimeMap = @{ 'x64' = 'win-x64'; 'arm64' = 'win-arm64' }
Write-BuildLog "Target architectures: $($archs -join ', ')"
foreach ($arch in $archs) {
$runtime = $runtimeMap[$arch]
$outputPath = Join-Path $OutputDir $arch
if (-not (Test-Path $outputPath)) {
New-Item -ItemType Directory -Path $outputPath -Force | Out-Null
}
# Build CLI
$cliProject = Join-Path $SrcDir "CLI\StartSet.CLI.csproj"
Publish-Binary -Name "StartSet CLI" -ProjectPath $cliProject -RuntimeIdentifier $runtime -OutputPath $outputPath -Version $Version
# Rename CLI executable
$cliExe = Join-Path $outputPath "StartSet.CLI.exe"
$targetCliExe = Join-Path $outputPath "managedstatekeeper.exe"
if (Test-Path $cliExe) {
Move-Item $cliExe $targetCliExe -Force
}
# Build Service
$serviceProject = Join-Path $SrcDir "Service\StartSet.Service.csproj"
Publish-Binary -Name "StartSet Service" -ProjectPath $serviceProject -RuntimeIdentifier $runtime -OutputPath $outputPath -Version $Version
# Rename Service executable
$serviceExe = Join-Path $outputPath "StartSet.Service.exe"
$targetServiceExe = Join-Path $outputPath "StartSetService.exe"
if (Test-Path $serviceExe) {
Move-Item $serviceExe $targetServiceExe -Force
}
# Clean up PDB files
Get-ChildItem -Path $outputPath -Filter "*.pdb" | Remove-Item -Force
}
Write-BuildLog "All binaries built successfully" -Level 'SUCCESS'
}
#endregion
#region Signing Functions
function Invoke-SignAllBinaries {
param(
[string]$Thumbprint,
[string]$CertStore
)
Write-BuildLog "Signing all executables..."
Test-SignTool
# Force garbage collection to release file handles
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Start-Sleep -Seconds 2
$archs = if ($Architecture -eq 'both') { @('x64', 'arm64') } elseif ($Architecture -eq 'x64') { @('x64') } else { @('arm64') }
foreach ($arch in $archs) {
$archDir = Join-Path $OutputDir $arch
$exeFiles = Get-ChildItem -Path $archDir -Filter "*.exe" -File -ErrorAction SilentlyContinue
foreach ($exe in $exeFiles) {
try {
Invoke-SignArtifact -Path $exe.FullName -Thumbprint $Thumbprint -Store $CertStore
}
catch {
Write-BuildLog "Failed to sign $($exe.Name): $_" -Level 'WARNING'
}
}
}
Write-BuildLog "Binary signing complete" -Level 'SUCCESS'
}
#endregion
#region MSI Packaging Functions
function Build-MsiPackage {
param(
[string]$Arch,
[hashtable]$Version,
[switch]$Sign,
[string]$Thumbprint,
[string]$CertStore
)
Write-BuildLog "Building MSI for $Arch..." "INFO"
# Check for cimipkg
if (-not (Test-CimiPkg)) {
Write-BuildLog "cimipkg.exe not found. Build CimianTools first or add cimipkg to PATH." "ERROR"
return $null
}
$cimipkgPath = Get-CimiPkgPath
Write-BuildLog "Using cimipkg: $cimipkgPath" "INFO"
$binDir = Join-Path $OutputDir $Arch
if (-not (Test-Path $binDir)) {
Write-BuildLog "Binary directory not found: $binDir" "ERROR"
return $null
}
# Create temporary MSI build directory
$msiTempDir = Join-Path $OutputDir "msi_$Arch"
if (Test-Path $msiTempDir) {
Remove-Item $msiTempDir -Recurse -Force
}
New-Item -ItemType Directory -Path $msiTempDir -Force | Out-Null
# Create payload directory and copy binaries
$payloadDir = Join-Path $msiTempDir "payload"
New-Item -ItemType Directory -Path $payloadDir -Force | Out-Null
Write-BuildLog "Copying StartSet binaries for $Arch to MSI payload..." "INFO"
$binaries = @("managedstatekeeper.exe", "StartSetService.exe")
foreach ($binary in $binaries) {
$sourcePath = Join-Path $binDir $binary
if (Test-Path $sourcePath) {
Copy-Item $sourcePath $payloadDir -Force
Write-BuildLog "Copied $binary to MSI payload" "INFO"
} else {
Write-BuildLog "Binary not found: $sourcePath" "WARNING"
}
}
# Create scripts directory with pre/postinstall
$scriptsDir = Join-Path $msiTempDir "scripts"
New-Item -ItemType Directory -Path $scriptsDir -Force | Out-Null
$postinstallTemplatePath = Join-Path $BuildDir "pkg\postinstall.ps1"
if (Test-Path $postinstallTemplatePath) {
$postinstallContent = Get-Content $postinstallTemplatePath -Raw
$postinstallContent = $postinstallContent -replace '\{\{VERSION\}\}', $Version.Full
$postinstallContent | Set-Content (Join-Path $scriptsDir "postinstall.ps1") -Encoding UTF8
Write-BuildLog "Added postinstall.ps1 script" "INFO"
}
$preinstallTemplatePath = Join-Path $BuildDir "pkg\preinstall.ps1"
if (Test-Path $preinstallTemplatePath) {
$preinstallContent = Get-Content $preinstallTemplatePath -Raw
$preinstallContent = $preinstallContent -replace '\{\{VERSION\}\}', $Version.Full
$preinstallContent | Set-Content (Join-Path $scriptsDir "preinstall.ps1") -Encoding UTF8
Write-BuildLog "Added preinstall.ps1 script" "INFO"
}
# Create build-info.yaml from template
$buildInfoTemplatePath = Join-Path $BuildDir "pkg\build-info.yaml"
if (-not (Test-Path $buildInfoTemplatePath)) {
Write-BuildLog "build-info.yaml template not found: $buildInfoTemplatePath" "ERROR"
Remove-Item $msiTempDir -Recurse -Force -ErrorAction SilentlyContinue
return $null
}
$buildInfoContent = Get-Content $buildInfoTemplatePath -Raw
$buildInfoContent = $buildInfoContent -replace '\{\{VERSION\}\}', $Version.Full
$buildInfoContent = $buildInfoContent -replace '\{\{ARCHITECTURE\}\}', $Arch
$buildInfoContent | Set-Content (Join-Path $msiTempDir "build-info.yaml") -Encoding UTF8
Write-BuildLog "Created build-info.yaml for MSI" "INFO"
# Build MSI using cimipkg (default format is MSI)
try {
$cimipkgArgs = @("--verbose")
if ($Sign -and $Thumbprint) {
$cimipkgArgs += @("--sign-thumbprint", $Thumbprint)
}
$cimipkgArgs += $msiTempDir
$process = Start-Process -FilePath $cimipkgPath -ArgumentList $cimipkgArgs -Wait -NoNewWindow -PassThru
if ($process.ExitCode -eq 0) {
# Look for the created .msi in the build subdirectory
$cimipkgBuildDir = Join-Path $msiTempDir "build"
if (Test-Path $cimipkgBuildDir) {
$createdMsi = Get-ChildItem -Path $cimipkgBuildDir -Filter "*.msi" | Select-Object -First 1
if ($createdMsi) {
$finalName = "StartSet-$($Version.Full)-$Arch.msi"
$finalPath = Join-Path $OutputDir $finalName
Move-Item $createdMsi.FullName $finalPath -Force
$msiSize = (Get-Item $finalPath).Length / 1MB
Write-BuildLog "MSI created: $finalName ($($msiSize.ToString('F2')) MB)" "SUCCESS"
Remove-Item $msiTempDir -Recurse -Force -ErrorAction SilentlyContinue
return $finalPath
}
}
Write-BuildLog "MSI file not found in cimipkg build directory" "WARNING"
} else {
Write-BuildLog "cimipkg failed with exit code $($process.ExitCode)" "ERROR"
}
}
catch {
Write-BuildLog "Failed to create MSI package: $_" "ERROR"
}
# Clean up temp directory on failure
Remove-Item $msiTempDir -Recurse -Force -ErrorAction SilentlyContinue
return $null
}
#endregion
#region NuGet Packaging Functions
function Build-NuGetPackage {
param(
[string]$Arch,
[hashtable]$Version,
[switch]$Sign,
[string]$Thumbprint
)
Write-BuildLog "Creating NuGet package for $Arch..." "INFO"
# Check for nuget
if (-not (Test-Command "nuget")) {
Write-BuildLog "nuget.exe not found - skipping NuGet package creation" "WARNING"
return $null
}
# Use template from build/nupkg/
$templatePath = Join-Path $BuildDir "nupkg\StartSet.nuspec.template"
if (-not (Test-Path $templatePath)) {
Write-BuildLog "NuGet template not found: $templatePath" "ERROR"
return $null
}
# Create temp nuspec directory
$tempNuspecDir = Join-Path $env:TEMP "StartSet-nupkg-$Arch-$(Get-Random)"
New-Item -ItemType Directory -Path $tempNuspecDir -Force | Out-Null
$nuspecPath = Join-Path $tempNuspecDir "StartSet.$Arch.nuspec"
# Read template and replace placeholders
$nuspecContent = Get-Content $templatePath -Raw
$nuspecContent = $nuspecContent -replace '{{VERSION}}', $Version.Semantic
$nuspecContent = $nuspecContent -replace '{{ARCHITECTURE}}', $Arch
$nuspecContent | Set-Content -Path $nuspecPath -Encoding UTF8
Write-BuildLog "Created nuspec from template for $Arch" "INFO"
$nupkgOutput = Join-Path $OutputDir "StartSet-$Arch.$($Version.Semantic).nupkg"
# Pack
& nuget pack $nuspecPath -OutputDirectory $OutputDir -BasePath $tempNuspecDir -NoDefaultExcludes
# Cleanup temp directory
Remove-Item $tempNuspecDir -Recurse -Force -ErrorAction SilentlyContinue
if ($LASTEXITCODE -ne 0) {
Write-BuildLog "NuGet pack failed for $Arch" "WARNING"
return $null
}
# Find and rename the package
$builtPkg = Get-ChildItem $OutputDir -Filter "StartSet-$Arch*.nupkg" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if ($builtPkg -and $builtPkg.FullName -ne $nupkgOutput) {
Move-Item $builtPkg.FullName $nupkgOutput -Force
}
if (Test-Path $nupkgOutput) {
Write-BuildLog "Created NuGet package: $(Split-Path $nupkgOutput -Leaf)" "SUCCESS"
if ($Sign) {
Invoke-SignNuget -NupkgPath $nupkgOutput -Thumbprint $Thumbprint
}
return $nupkgOutput
}
Write-BuildLog "NuGet package not found after build" "WARNING"
return $null
}
#endregion
#region PKG Packaging Functions
function Build-PkgPackage {
param(
[Parameter(Mandatory)][string]$Arch,
[Parameter(Mandatory)][hashtable]$Version,
[switch]$Sign,
[string]$Thumbprint,
[string]$Store
)
Write-BuildLog "Creating .pkg package for $Arch..." "INFO"
# Check for cimipkg
if (-not (Test-CimiPkg)) {
Write-BuildLog "cimipkg.exe not found. Build CimianToolsGo first or add cimipkg to PATH." "ERROR"
return $null
}
$cimipkgPath = Get-CimiPkgPath
Write-BuildLog "Using cimipkg: $cimipkgPath" "INFO"
$binDir = Join-Path $OutputDir $Arch
if (-not (Test-Path $binDir)) {
Write-BuildLog "Binary directory not found: $binDir" "ERROR"
return $null
}
# Create temporary .pkg build directory
$pkgTempDir = Join-Path $OutputDir "pkg_$Arch"
if (Test-Path $pkgTempDir) {
Remove-Item $pkgTempDir -Recurse -Force
}
New-Item -ItemType Directory -Path $pkgTempDir -Force | Out-Null
# Create payload directory and copy binaries
$payloadDir = Join-Path $pkgTempDir "payload"
New-Item -ItemType Directory -Path $payloadDir -Force | Out-Null
Write-BuildLog "Copying StartSet binaries for $Arch architecture to .pkg payload..." "INFO"
$binaries = @(
"managedstatekeeper.exe",
"StartSetService.exe"
)
foreach ($binary in $binaries) {
$sourcePath = Join-Path $binDir $binary
if (Test-Path $sourcePath) {
Copy-Item $sourcePath $payloadDir -Force
Write-BuildLog "Copied $binary to .pkg payload" "INFO"
} else {
Write-BuildLog "Binary not found: $sourcePath" "WARNING"
}
}
# Create scripts directory and copy pre/postinstall scripts
$scriptsDir = Join-Path $pkgTempDir "scripts"
New-Item -ItemType Directory -Path $scriptsDir -Force | Out-Null
# Copy and process postinstall script from build/pkg/ template
$postinstallTemplatePath = Join-Path $BuildDir "pkg\postinstall.ps1"
if (Test-Path $postinstallTemplatePath) {
$postinstallContent = Get-Content $postinstallTemplatePath -Raw
$postinstallContent = $postinstallContent -replace '\{\{VERSION\}\}', $Version.Full
$postinstallContent | Set-Content (Join-Path $scriptsDir "postinstall.ps1") -Encoding UTF8
Write-BuildLog "Added postinstall.ps1 script to .pkg" "INFO"
} else {
Write-BuildLog "Postinstall template not found: $postinstallTemplatePath" "WARNING"
}
# Copy and process preinstall script from build/pkg/ template
$preinstallTemplatePath = Join-Path $BuildDir "pkg\preinstall.ps1"
if (Test-Path $preinstallTemplatePath) {
$preinstallContent = Get-Content $preinstallTemplatePath -Raw
$preinstallContent = $preinstallContent -replace '\{\{VERSION\}\}', $Version.Full
$preinstallContent | Set-Content (Join-Path $scriptsDir "preinstall.ps1") -Encoding UTF8
Write-BuildLog "Added preinstall.ps1 script to .pkg" "INFO"
} else {
Write-BuildLog "Preinstall template not found: $preinstallTemplatePath" "WARNING"
}
# Copy and process build-info.yaml from build/pkg/ template
$buildInfoTemplatePath = Join-Path $BuildDir "pkg\build-info.yaml"
if (Test-Path $buildInfoTemplatePath) {
$buildInfoContent = Get-Content $buildInfoTemplatePath -Raw
$buildInfoContent = $buildInfoContent -replace '\{\{VERSION\}\}', $Version.Full
$buildInfoContent = $buildInfoContent -replace '\{\{ARCHITECTURE\}\}', $Arch
if ($Sign -and $Thumbprint) {
$buildInfoContent += @"
code_signing:
enabled: true
certificate_thumbprint: $Thumbprint
certificate_store: $Store
"@
}
$buildInfoPath = Join-Path $pkgTempDir "build-info.yaml"
$buildInfoContent | Set-Content $buildInfoPath -Encoding UTF8
Write-BuildLog "Created build-info.yaml for .pkg" "INFO"
} else {
Write-BuildLog "build-info.yaml template not found: $buildInfoTemplatePath" "ERROR"
return $null
}
# Build the .pkg package using cimipkg
Write-BuildLog "Building .pkg package for $Arch architecture..." "INFO"
try {
$cimipkgArgs = @("--verbose", $pkgTempDir)
$process = Start-Process -FilePath $cimipkgPath -ArgumentList $cimipkgArgs -Wait -NoNewWindow -PassThru
if ($process.ExitCode -eq 0) {
Write-BuildLog ".pkg package created successfully for ${Arch}" "SUCCESS"
# Look for the created .pkg file in the build subdirectory
$buildDir = Join-Path $pkgTempDir "build"
if (Test-Path $buildDir) {
$createdPkgFiles = Get-ChildItem -Path $buildDir -Filter "*.pkg"
foreach ($pkgFile in $createdPkgFiles) {
# Move the .pkg to the release directory with proper naming
$pkgName = "StartSet-$($Version.Full)-$Arch.pkg"
$finalPkgPath = Join-Path $OutputDir $pkgName
Move-Item $pkgFile.FullName $finalPkgPath -Force
$pkgSize = (Get-Item $finalPkgPath).Length / 1MB
Write-BuildLog ".pkg created: $pkgName ($($pkgSize.ToString('F2')) MB)" "SUCCESS"
# Clean up temp directory
Remove-Item $pkgTempDir -Recurse -Force -ErrorAction SilentlyContinue
return $finalPkgPath
}
}
Write-BuildLog ".pkg file not found in build directory" "WARNING"
} else {
Write-BuildLog "cimipkg failed with exit code $($process.ExitCode)" "ERROR"
}
}
catch {
Write-BuildLog "Failed to create .pkg package: $_" "ERROR"
}
# Clean up temp directory on failure
Remove-Item $pkgTempDir -Recurse -Force -ErrorAction SilentlyContinue
return $null
}
#endregion
#region IntuneWin Packaging Functions