-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
2893 lines (2525 loc) · 133 KB
/
Program.cs
File metadata and controls
2893 lines (2525 loc) · 133 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
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.IO.Compression;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Win32;
namespace BootstrapMate
{
class Program
{
// Windows API calls for suppressing system sounds
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool Beep(uint dwFreq, uint dwDuration);
[DllImport("user32.dll")]
static extern bool MessageBeep(uint uType);
[DllImport("winmm.dll")]
static extern int waveOutSetVolume(int hwo, uint dwVolume);
[DllImport("winmm.dll")]
static extern int waveOutGetVolume(int hwo, out uint dwVolume);
// System sound suppression
private static uint originalVolume = 0;
private static bool soundsSuppressed = false;
private static string LogDirectory = @"C:\ProgramData\ManagedBootstrap\logs";
private static string CacheDirectory = @"C:\ProgramData\ManagedBootstrap\cache";
// Version in YYYY.MM.DD.HHMM format - injected at build time via MSBuild
private static readonly string Version = GetBuildVersion();
private static string GetBuildVersion()
{
// Get version from assembly metadata (injected by MSBuild at compile time)
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var attribute = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyMetadataAttribute), false)
.Cast<System.Reflection.AssemblyMetadataAttribute>()
.FirstOrDefault(a => a.Key == "BuildTimestamp");
return attribute?.Value ?? "dev.build";
}
static string GetCacheDirectory()
{
try
{
Directory.CreateDirectory(CacheDirectory);
return CacheDirectory;
}
catch (Exception ex)
{
Logger.Warning($"Could not create cache directory {CacheDirectory}: {ex.Message}");
Logger.Debug("Falling back to temp directory for cache");
// Fallback to temp directory if we can't create the ProgramData cache
string fallbackDir = Path.Combine(Path.GetTempPath(), "BootstrapMate");
Directory.CreateDirectory(fallbackDir);
return fallbackDir;
}
}
/// <summary>
/// Temporarily suppress system sounds to prevent alert sounds during silent installations
/// </summary>
static void SuppressSystemSounds()
{
try
{
// Get current system volume for restoration later
waveOutGetVolume(0, out originalVolume);
// Set system volume to 0 (mute system sounds)
waveOutSetVolume(0, 0);
soundsSuppressed = true;
Logger.Debug("System sounds suppressed for silent installation");
}
catch (Exception ex)
{
Logger.Debug($"Could not suppress system sounds: {ex.Message}");
// Continue anyway - this is not critical
}
}
/// <summary>
/// Restore system sounds to original levels
/// </summary>
static void RestoreSystemSounds()
{
try
{
if (soundsSuppressed)
{
// Restore original system volume
waveOutSetVolume(0, originalVolume);
soundsSuppressed = false;
Logger.Debug("System sounds restored to original levels");
}
}
catch (Exception ex)
{
Logger.Debug($"Could not restore system sounds: {ex.Message}");
// Continue anyway - this is not critical
}
}
static bool IsRunningAsAdministrator()
{
try
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
static bool TryRestartAsAdministrator(string[] args)
{
try
{
// Check if we're in silent mode - if so, don't try to restart with GUI
bool silentMode = args.Any(arg => arg.Equals("--silent", StringComparison.OrdinalIgnoreCase));
if (silentMode)
{
Logger.Error("Running in silent mode but not elevated - cannot show UAC prompt");
return false;
}
var startInfo = new ProcessStartInfo
{
FileName = Environment.ProcessPath ?? Path.Combine(AppContext.BaseDirectory, "installapplications.exe"),
Arguments = string.Join(" ", args),
UseShellExecute = true,
Verb = "runas", // Request elevation
CreateNoWindow = true, // Don't create console window
WindowStyle = ProcessWindowStyle.Hidden
};
Logger.Info("BootstrapMate requires administrator privileges. Requesting elevation...");
Console.WriteLine("BootstrapMate requires administrator privileges. Requesting elevation...");
using var process = Process.Start(startInfo);
if (process != null)
{
Logger.Info($"Elevated process started with PID: {process.Id}");
Console.WriteLine("Elevated process started. This instance will now exit.");
return true;
}
else
{
Logger.Warning("Failed to start elevated process - user may have denied elevation");
Console.WriteLine("Failed to start elevated process. User may have denied elevation.");
return false;
}
}
catch (Exception ex)
{
Logger.Error($"Error attempting to restart as administrator: {ex.Message}");
Console.WriteLine($"Error attempting to restart as administrator: {ex.Message}");
return false;
}
}
// Legacy WriteLog method for compatibility with StatusManager
static void WriteLog(string message)
{
Logger.Debug(message);
}
static int Main(string[] args)
{
// Handle version request immediately without admin check or verbose logging
if (args.Length > 0 && (args[0].Equals("--version", StringComparison.OrdinalIgnoreCase) ||
args[0].Equals("-v", StringComparison.OrdinalIgnoreCase)))
{
Console.WriteLine(Version);
return 0;
}
// Check for silent mode - suppress all console output
bool silentMode = args.Any(arg => arg.Equals("--silent", StringComparison.OrdinalIgnoreCase));
// Check for verbose mode
bool verboseMode = args.Any(arg => arg.Equals("--verbose", StringComparison.OrdinalIgnoreCase) ||
arg.Equals("-v", StringComparison.OrdinalIgnoreCase));
Logger.Initialize(LogDirectory, Version, verboseMode, silentMode);
Logger.Debug("Main() called with arguments: " + string.Join(" ", args));
// Check if running as administrator
if (!IsRunningAsAdministrator())
{
if (!silentMode)
{
// Immediate clear message without logger initialization noise
Console.WriteLine();
Console.WriteLine("ERROR: BootstrapMate must be run as Administrator");
Console.WriteLine();
Console.WriteLine(" BootstrapMate requires elevated privileges to:");
Console.WriteLine(" • Install packages to Program Files");
Console.WriteLine(" • Write to HKLM registry keys");
Console.WriteLine(" • Install Windows services");
Console.WriteLine(" • Manage system components");
Console.WriteLine();
Console.WriteLine(" Please run BootstrapMate as Administrator, or use:");
Console.WriteLine($" sudo {Path.GetFileName(Environment.ProcessPath ?? "installapplications.exe")} {string.Join(" ", args)}");
Console.WriteLine();
}
Logger.Info("BootstrapMate is not running as Administrator");
if (!silentMode)
{
// Ask user if they want to restart as admin
Console.Write(" Would you like to restart as Administrator? (y/n): ");
var response = Console.ReadLine()?.Trim().ToLowerInvariant();
if (response == "y" || response == "yes")
{
Console.WriteLine(" Attempting to restart with administrator privileges...");
// Attempt to restart as administrator
if (TryRestartAsAdministrator(args))
{
Logger.Info("Successfully launched elevated process. Exiting current instance.");
return 0; // Success - elevated process will handle the work
}
else
{
Logger.Error("Failed to obtain administrator privileges. Cannot continue.");
Console.WriteLine(" ERROR: Failed to restart with administrator privileges.");
Console.WriteLine(" Please manually run as Administrator or use sudo.");
return 1; // Error - elevation failed
}
}
else
{
Logger.Error("User declined to restart as administrator. Cannot continue.");
Console.WriteLine(" Operation cancelled. BootstrapMate requires administrator privileges.");
return 1; // Error - user declined elevation
}
}
else
{
// In silent mode, just attempt to restart as administrator automatically
if (TryRestartAsAdministrator(args))
{
Logger.Info("Successfully launched elevated process in silent mode. Exiting current instance.");
return 0; // Success - elevated process will handle the work
}
else
{
Logger.Error("Failed to obtain administrator privileges in silent mode. Cannot continue.");
return 1; // Error - elevation failed
}
}
}
Logger.Debug("Running with administrator privileges");
if (!silentMode)
{
Console.WriteLine("[+] Running with administrator privileges");
Console.WriteLine();
}
return MainAsync(args).GetAwaiter().GetResult();
}
static async Task<int> MainAsync(string[] args)
{
// Check for silent mode flag
bool silentMode = args.Any(arg => arg.Equals("--silent", StringComparison.OrdinalIgnoreCase));
if (!silentMode)
{
Logger.WriteHeader($"BootstrapMate for Windows v{Version}");
Console.WriteLine("MDM-agnostic bootstrapping tool for Windows");
Console.WriteLine("Windows Admins Open Source 2025");
}
// Clean up old statuses (older than 24 hours) on startup
try
{
StatusManager.CleanupOldStatuses(TimeSpan.FromHours(24));
Logger.Debug("Cleaned up old installation statuses");
}
catch (Exception ex)
{
Logger.Warning($"Failed to cleanup old statuses: {ex.Message}");
}
// Clean up all cached packages on startup (cache only contains failed installations for inspection)
try
{
CleanupOldCache(TimeSpan.Zero);
Logger.Debug("Cleaned up cached files from previous runs (failed installations only)");
}
catch (Exception ex)
{
Logger.Warning($"Failed to cleanup old cache files: {ex.Message}");
}
// Parse command line arguments
bool forceDownload = false;
bool noDialog = false;
string dialogTitle = "Setting Up Your Device";
string dialogMessage = "Please wait while we install required software...";
string manifestUrl = "";
if (args.Length == 0)
{
if (!silentMode)
{
Console.WriteLine("Usage:");
Console.WriteLine(" installapplications.exe --url <manifest-url>");
Console.WriteLine(" installapplications.exe --help");
Console.WriteLine(" installapplications.exe --version");
Console.WriteLine(" installapplications.exe --status");
Console.WriteLine(" installapplications.exe --clear-cache");
Console.WriteLine(" installapplications.exe --reset-chocolatey");
Console.WriteLine(" installapplications.exe --url <manifest-url> --force");
Console.WriteLine(" installapplications.exe --url <manifest-url> --verbose");
Console.WriteLine(" installapplications.exe --url <manifest-url> --silent");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" --url <url> URL to the bootstrapmate.json manifest");
Console.WriteLine(" --force (Deprecated - downloads are always fresh. Cache is for inspection only)");
Console.WriteLine(" --verbose Show detailed logging output");
Console.WriteLine(" --silent Run completely silently (no console output)");
Console.WriteLine(" --no-dialog Disable progress dialog (csharpdialog)");
Console.WriteLine(" --dialog-title Custom title for progress dialog");
Console.WriteLine(" --dialog-message Custom message for progress dialog");
Console.WriteLine(" --help Show this help message");
Console.WriteLine(" --version Show version information");
Console.WriteLine(" --status Show current installation status");
Console.WriteLine(" --clear-status Clear all installation status data");
Console.WriteLine(" --clear-cache Clear all caches including failed installation files (BootstrapMate + Chocolatey)");
Console.WriteLine(" --reset-chocolatey Complete Chocolatey reset (removes corrupted lib folder)");
}
return 0;
}
for (int i = 0; i < args.Length; i++)
{
switch (args[i].ToLower())
{
case "--help":
case "-h":
Console.WriteLine("BootstrapMate Help");
Console.WriteLine("========================");
Console.WriteLine();
Console.WriteLine("This tool downloads and processes a bootstrapmate.json manifest file");
Console.WriteLine("to automatically install packages during Windows OOBE or setup scenarios.");
Console.WriteLine();
Console.WriteLine("Usage Examples:");
Console.WriteLine(" installapplications.exe --url https://example.com/bootstrap/bootstrapmate.json");
Console.WriteLine();
Console.WriteLine("Features:");
Console.WriteLine(" - Supports multiple package types: MSI, EXE, PowerShell, Chocolatey (.nupkg), sbin-installer (.pkg)");
Console.WriteLine(" - Handles setupassistant (OOBE) and userland installation phases");
Console.WriteLine(" - Admin privilege escalation for elevated packages");
Console.WriteLine(" - Architecture-specific conditional installation");
Console.WriteLine(" - Registry-based status tracking for detection scripts");
Console.WriteLine(" - Primary installer: sbin-installer (lightweight, fast)");
return 0;
case "--status":
return ShowStatus();
case "--clear-status":
return ClearStatus();
case "--clear-cache":
return ClearCache();
case "--reset-chocolatey":
return ResetChocolatey();
case "--force":
forceDownload = true;
break;
case "--verbose":
// Verbose mode is already handled in Main()
break;
case "--silent":
// Silent mode is already handled in Main()
break;
case "--url":
if (i + 1 < args.Length)
{
manifestUrl = args[i + 1];
i++; // Skip the next argument since we consumed it
}
else
{
Console.WriteLine("ERROR: --url requires a URL parameter");
return 1;
}
break;
case "--no-dialog":
noDialog = true;
break;
case "--dialog-title":
if (i + 1 < args.Length)
{
dialogTitle = args[i + 1];
i++;
}
break;
case "--dialog-message":
if (i + 1 < args.Length)
{
dialogMessage = args[i + 1];
i++;
}
break;
}
}
// Process manifest if URL was provided
if (!string.IsNullOrEmpty(manifestUrl))
{
return await ProcessManifest(manifestUrl, forceDownload, noDialog, dialogTitle, dialogMessage);
}
Console.WriteLine("ERROR: Invalid arguments. Use --help for usage information.");
return 1;
}
static async Task<int> ProcessManifest(string manifestUrl, bool forceDownload = false, bool noDialog = false, string dialogTitle = "Setting Up Your Device", string dialogMessage = "Please wait while we install required software...")
{
try
{
// Suppress system sounds for silent installation experience
SuppressSystemSounds();
// Clear cache if force download is requested
if (forceDownload)
{
Logger.Debug("Force download requested - aggressively clearing all caches");
Logger.Info("Force download requested - aggressively clearing all caches");
ClearAllCachesAggressive();
}
// Initialize status tracking
StatusManager.Initialize(manifestUrl, Version);
Logger.Debug($"Initialized status tracking with RunId: {StatusManager.GetCurrentRunId()}");
Logger.Info($"Downloading manifest from: {manifestUrl}");
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", $"BootstrapMate/{Version}");
string jsonContent = await httpClient.GetStringAsync(manifestUrl);
Logger.Debug("Manifest downloaded successfully");
// Parse the JSON manifest
using var doc = JsonDocument.Parse(jsonContent);
var root = doc.RootElement;
// Count total packages for dialog progress
int totalPackages = 0;
if (root.TryGetProperty("setupassistant", out var setupCount))
{
totalPackages += setupCount.GetArrayLength();
}
if (root.TryGetProperty("userland", out var userlandCount))
{
totalPackages += userlandCount.GetArrayLength();
}
// Initialize dialog (gracefully degrades if not available)
if (!noDialog)
{
DialogManager.Instance.Initialize(
dialogTitle,
dialogMessage,
totalPackages,
icon: null,
fullScreen: false,
kioskMode: false
);
// Add list items for all packages
if (root.TryGetProperty("setupassistant", out var setupPkgs))
{
foreach (var pkg in setupPkgs.EnumerateArray())
{
var name = pkg.GetProperty("name").GetString() ?? "Unknown";
DialogManager.Instance.AddListItem(name, DialogStatus.Pending);
}
}
if (root.TryGetProperty("userland", out var userlandPkgs))
{
foreach (var pkg in userlandPkgs.EnumerateArray())
{
var name = pkg.GetProperty("name").GetString() ?? "Unknown";
DialogManager.Instance.AddListItem(name, DialogStatus.Pending);
}
}
}
// Process setupassistant packages first
if (root.TryGetProperty("setupassistant", out var setupAssistant))
{
StatusManager.SetPhaseStatus(InstallationPhase.SetupAssistant, InstallationStage.Starting);
Logger.WriteSection("Processing Setup Assistant packages");
DialogManager.Instance.NotifyPhaseStarted("Setup Assistant");
StatusManager.SetPhaseStatus(InstallationPhase.SetupAssistant, InstallationStage.Running);
try
{
await ProcessPackages(setupAssistant, "setupassistant", forceDownload);
StatusManager.SetPhaseStatus(InstallationPhase.SetupAssistant, InstallationStage.Completed);
Logger.Debug("Setup Assistant packages completed successfully");
}
catch (Exception ex)
{
StatusManager.SetPhaseStatus(InstallationPhase.SetupAssistant, InstallationStage.Failed, ex.Message, 1);
throw; // Re-throw to maintain existing error handling
}
}
else
{
// Mark as skipped if no setupassistant packages
StatusManager.SetPhaseStatus(InstallationPhase.SetupAssistant, InstallationStage.Skipped);
Logger.Debug("No Setup Assistant packages found - marked as skipped");
}
// Process userland packages
if (root.TryGetProperty("userland", out var userland))
{
StatusManager.SetPhaseStatus(InstallationPhase.Userland, InstallationStage.Starting);
Logger.Debug("Processing Userland packages...");
Logger.WriteSection("Processing Userland packages");
DialogManager.Instance.NotifyPhaseStarted("Userland");
StatusManager.SetPhaseStatus(InstallationPhase.Userland, InstallationStage.Running);
try
{
await ProcessPackages(userland, "userland", forceDownload);
StatusManager.SetPhaseStatus(InstallationPhase.Userland, InstallationStage.Completed);
Logger.Debug("Userland packages completed successfully");
}
catch (Exception ex)
{
StatusManager.SetPhaseStatus(InstallationPhase.Userland, InstallationStage.Failed, ex.Message, 1);
throw; // Re-throw to maintain existing error handling
}
}
else
{
// Mark as skipped if no userland packages
StatusManager.SetPhaseStatus(InstallationPhase.Userland, InstallationStage.Skipped);
Logger.Debug("No Userland packages found - marked as skipped");
}
Logger.Debug("BootstrapMate completed successfully!");
Logger.WriteCompletion("BootstrapMate completed successfully!");
// Mark dialog as complete and close it
DialogManager.Instance.Complete("Setup Complete!");
await Task.Delay(2000); // Give user time to see completion message
DialogManager.Instance.Close();
// Write successful completion to registry for Intune detection
StatusManager.WriteSuccessfulCompletionRegistry();
// Restore system sounds before completion
RestoreSystemSounds();
return 0;
}
catch (Exception ex)
{
// Ensure sounds are restored even on error
RestoreSystemSounds();
// Close dialog on error
try
{
DialogManager.Instance.UpdateProgressText("Setup failed - please contact IT support");
DialogManager.Instance.TerminateDialog();
}
catch { }
Logger.Error($"Error processing manifest: {ex.Message}");
Logger.Debug($"Stack trace: {ex.StackTrace}");
Logger.WriteError($"Error processing manifest: {ex.Message}");
// Ensure status is marked as failed on any unhandled exception
try
{
// Try to determine which phase failed based on current state
var setupStatus = StatusManager.GetPhaseStatus(InstallationPhase.SetupAssistant);
var userlandStatus = StatusManager.GetPhaseStatus(InstallationPhase.Userland);
if (setupStatus.Stage == InstallationStage.Running)
{
StatusManager.SetPhaseStatus(InstallationPhase.SetupAssistant, InstallationStage.Failed, ex.Message, 1);
}
else if (userlandStatus.Stage == InstallationStage.Running)
{
StatusManager.SetPhaseStatus(InstallationPhase.Userland, InstallationStage.Failed, ex.Message, 1);
}
}
catch
{
// Don't let status update failures mask the original error
}
return 1;
}
}
static int GetPackageProcessingPriority(JsonElement package)
{
try
{
var type = package.GetProperty("type").GetString()?.ToLowerInvariant() ?? "";
var name = package.GetProperty("name").GetString()?.ToLowerInvariant() ?? "";
// Priority levels (lower number = higher priority = processed first):
// Priority 1: Essential system installers that other packages might depend on
if (type == "msi" || type == "exe")
{
return 1;
}
// Priority 2: Chocolatey packages (.nupkg) - these install Chocolatey if needed
if (type == "nupkg")
{
return 2;
}
// Priority 3: General PowerShell scripts (but not cleanup scripts)
if (type == "powershell" || type == "ps1")
{
// Check if this is a cleanup/maintenance script - these should run last
if (name.Contains("cleanup") || name.Contains("clean") ||
name.Contains("wipe") || name.Contains("remove") ||
name.Contains("delete") || name.Contains("purge") ||
name.Contains("nuclear") || name.Contains("maintenance"))
{
return 10; // Run cleanup scripts last
}
return 3; // Regular PowerShell scripts
}
// Priority 5: Unknown or other types
return 5;
}
catch
{
// If we can't determine priority, use default middle priority
return 5;
}
}
static async Task ProcessPackages(JsonElement packages, string phase, bool forceDownload = false)
{
Logger.Debug($"Processing packages for phase: {phase}");
// Convert JsonElement array to list for sorting
var packageList = packages.EnumerateArray().ToList();
// Reorder packages to prevent race conditions:
// 1. Install packages that might install tools (nupkg, msi, exe) first
// 2. Run cleanup/maintenance scripts last to avoid breaking tools needed by other packages
var sortedPackages = packageList.OrderBy(pkg => GetPackageProcessingPriority(pkg)).ToList();
// Log reordering information if packages were reordered
if (!packageList.SequenceEqual(sortedPackages))
{
Logger.Info("Optimizing package installation order to prevent dependency conflicts");
Logger.Debug("Package processing order optimized to prevent dependency conflicts:");
for (int i = 0; i < sortedPackages.Count; i++)
{
var pkg = sortedPackages[i];
var name = pkg.GetProperty("name").GetString() ?? "Unknown";
var type = pkg.GetProperty("type").GetString() ?? "";
Logger.Debug($" {i + 1}. {name} (Type: {type})");
}
Logger.Info("This ensures cleanup scripts run after packages that might need the tools being cleaned");
}
foreach (var package in sortedPackages)
{
string displayName = "Unknown Package"; // Default value for error handling
try
{
displayName = package.GetProperty("name").GetString() ?? "Unknown";
var url = package.GetProperty("url").GetString() ?? "";
var fileName = package.GetProperty("file").GetString() ?? "";
var type = package.GetProperty("type").GetString() ?? "";
Logger.Debug($"Processing package: {displayName} (Type: {type}, File: {fileName})");
Logger.WriteProgress("Processing", displayName);
// Check architecture condition if specified
if (package.TryGetProperty("condition", out var condition))
{
var conditionStr = condition.GetString() ?? "";
Logger.Debug($"Checking condition: {conditionStr}");
// Get actual OS architecture - use OSArchitecture (not ProcessArchitecture) so that
// the x64 binary running under ARM64 emulation still correctly detects ARM64.
string actualArchitecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString().ToUpperInvariant();
Logger.Debug($"Detected OS architecture: {actualArchitecture}");
// Skip x64 packages on non-x64 systems
// Note: RuntimeInformation reports "X64" for AMD64/Intel 64-bit, "ARM64" for ARM64
if (conditionStr.Contains("architecture_x64") && actualArchitecture != "X64")
{
Logger.Debug($"Skipping {displayName} - x64 condition not met on {actualArchitecture} architecture");
Logger.WriteSkipped($"Skipping - x64 condition not met on {actualArchitecture}");
DialogManager.Instance.NotifyPackageSkipped(displayName, "Architecture mismatch");
continue;
}
// Skip ARM64 packages on non-ARM64 systems
if (conditionStr.Contains("architecture_arm64") && actualArchitecture != "ARM64")
{
Logger.Debug($"Skipping {displayName} - ARM64 condition not met on {actualArchitecture} architecture");
Logger.WriteSkipped($"Skipping - ARM64 condition not met on {actualArchitecture}");
DialogManager.Instance.NotifyPackageSkipped(displayName, "Architecture mismatch");
continue;
}
}
await DownloadAndInstallPackage(displayName, url, fileName, type, package, forceDownload);
Logger.Debug($"Successfully completed package: {displayName}");
Logger.WriteSuccess($"{displayName} installed successfully");
DialogManager.Instance.NotifyPackageSuccess(displayName);
}
catch (Exception ex)
{
Logger.Error($"Failed to install package {displayName}: {ex.Message}");
Logger.WriteError($"Failed to install package {displayName}: {ex.Message}");
DialogManager.Instance.NotifyPackageFailure(displayName, "Failed");
// Continue with next package instead of stopping entire process
// Note: We don't re-throw because we want to continue with other packages
}
}
}
static async Task DownloadAndInstallPackage(string displayName, string url, string fileName, string type, JsonElement packageInfo, bool forceDownload = false)
{
// Create cache download directory (keeps failed installations for inspection)
string cacheDir = GetCacheDirectory();
string localPath = Path.Combine(cacheDir, fileName);
try
{
// Always download fresh files - cache is only for inspection/debugging
// Delete existing cached file if present to ensure fresh download
if (File.Exists(localPath))
{
try
{
File.Delete(localPath);
Logger.Debug($"Deleted old cached file: {localPath}");
}
catch (Exception ex)
{
Logger.Warning($"Could not delete old cached file {localPath}: {ex.Message}");
}
}
Logger.Debug($"Downloading {displayName} from: {url}");
Logger.WriteSubProgress("Downloading from", url);
DialogManager.Instance.NotifyDownloadStarted(displayName);
using var httpClient = new HttpClient();
using var response = await httpClient.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Download failed: {response.StatusCode}");
}
// Ensure the file stream is completely closed before proceeding
{
await using var fileStream = File.Create(localPath);
await response.Content.CopyToAsync(fileStream);
await fileStream.FlushAsync();
} // fileStream is disposed here
// Add a small delay to ensure file handle is released
await Task.Delay(100);
var fileInfo = new FileInfo(localPath);
Logger.Debug($"Downloaded {displayName} to: {localPath} (Size: {fileInfo.Length / 1024 / 1024:F2} MB)");
Logger.WriteSubProgress("Downloaded", $"{fileInfo.Length / 1024 / 1024:F1} MB");
// Install based on type
Logger.Debug($"Installing {displayName} using {type} installer...");
DialogManager.Instance.NotifyInstallStarted(displayName);
await InstallPackage(localPath, type, packageInfo);
Logger.Debug($"Successfully installed: {displayName}");
// Delete the cached file after successful installation
try
{
if (File.Exists(localPath))
{
File.Delete(localPath);
Logger.Debug($"Deleted cached file after successful installation: {localPath}");
}
}
catch (Exception deleteEx)
{
Logger.Warning($"Could not delete cached file after successful installation: {deleteEx.Message}");
}
}
catch (Exception ex)
{
Logger.Error($"Failed to install {displayName}: {ex.Message}");
Logger.Warning($"Keeping cached file for inspection: {localPath}");
// Re-throw the exception so the caller knows the installation failed
throw;
}
}
static async Task InstallPackage(string filePath, string type, JsonElement packageInfo)
{
Logger.Debug($"Installing package: {filePath} (Type: {type})");
switch (type.ToLower())
{
case "powershell":
case "ps1":
await RunPowerShellScript(filePath, packageInfo);
break;
case "msi":
await RunMsiInstaller(filePath, packageInfo);
break;
case "exe":
await RunExecutable(filePath, packageInfo);
break;
case "nupkg":
// Try sbin-installer first, fallback to Chocolatey
if (IsSbinInstallerAvailable())
{
await RunSbinInstall(filePath, packageInfo);
}
else
{
Logger.WriteSubProgress("sbin-installer not found", "Using Chocolatey fallback");
await RunChocolateyInstall(filePath, packageInfo);
}
break;
case "pkg":
// pkg format is native to sbin-installer
if (!IsSbinInstallerAvailable())
{
throw new Exception("sbin-installer is required for .pkg packages but was not found. Please install sbin-installer first.");
}
Logger.WriteSubProgress("Processing .pkg with sbin-installer");
await RunSbinInstall(filePath, packageInfo);
break;
default:
Logger.Warning($"Unknown package type: {type}");
Logger.WriteWarning($"Unknown package type: {type}");
throw new Exception($"Unsupported package type: {type}. Supported types are: msi, exe, ps1, nupkg, pkg");
}
}
static async Task RunPowerShellScript(string scriptPath, JsonElement packageInfo)
{
var args = GetArguments(packageInfo);
string arguments = $"-ExecutionPolicy Bypass -NoProfile -File \"{scriptPath}\" {string.Join(" ", args)}";
// Since BootstrapMate is already running as admin, all PowerShell scripts should inherit admin privileges
// This ensures chocolatey and other system installers work properly
bool needsElevation = true; // Always run elevated since we're in an admin context
WriteLog($"Running PowerShell script: {scriptPath}");
WriteLog($"Arguments: {arguments}");
WriteLog($"Elevated: {needsElevation}");
var startInfo = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = arguments,
UseShellExecute = false, // Use CreateProcess to inherit admin privileges
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
Console.WriteLine($" [>] Running PowerShell: {arguments}");
using var process = Process.Start(startInfo);
if (process != null)
{
await process.WaitForExitAsync();
// Capture output for debugging
if (startInfo.RedirectStandardOutput)
{
string output = await process.StandardOutput.ReadToEndAsync();
if (!string.IsNullOrWhiteSpace(output))
{
WriteLog($"PowerShell output: {output}");
}
}
if (startInfo.RedirectStandardError)
{
string error = await process.StandardError.ReadToEndAsync();
if (!string.IsNullOrWhiteSpace(error))
{
WriteLog($"PowerShell error: {error}");
}
}
WriteLog($"PowerShell script completed with exit code: {process.ExitCode}");
if (process.ExitCode != 0)
{
throw new Exception($"PowerShell script failed with exit code: {process.ExitCode}");
}
}
}
static bool RequiresElevation(string scriptPath, JsonElement packageInfo)
{
// Get the script filename to check for known patterns
string scriptFileName = Path.GetFileName(scriptPath).ToLowerInvariant();
// Get package name/ID for specific package checks
string packageName = "";
if (packageInfo.TryGetProperty("name", out var nameProp))
{
packageName = nameProp.GetString()?.ToLowerInvariant() ?? "";
}
string packageId = "";
if (packageInfo.TryGetProperty("packageid", out var idProp))
{
packageId = idProp.GetString()?.ToLowerInvariant() ?? "";
}
// Scripts that definitely need elevation
if (scriptFileName.Contains("chocolatey") ||
scriptFileName.Contains("install-chocolatey") ||
packageName.Contains("chocolatey") ||
packageId.Contains("chocolatey"))
{
return true;
}
// Any script that installs system-wide components needs elevation
if (scriptFileName.Contains("install") &&
(scriptFileName.Contains("system") || scriptFileName.Contains("global")))
{
return true;
}
// Package manager installers typically need elevation
if (packageName.Contains("package manager") ||
packageId.Contains("package-manager"))
{
return true;
}
return false;
}