-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-v1.ps1
More file actions
2411 lines (2032 loc) · 89.1 KB
/
setup-v1.ps1
File metadata and controls
2411 lines (2032 loc) · 89.1 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
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Development Environment Setup Script v2.0
.DESCRIPTION
This script sets up a complete development environment on Windows 10/11.
It installs essential development tools, configures PowerShell, VS Code, Git, and more.
.PARAMETER Mode
Installation mode: 'Full', 'Minimal', or 'Custom'. Default is 'Full'.
.PARAMETER SkipPackages
Comma-separated list of package names to skip during installation.
.PARAMETER SkipExtensions
Comma-separated list of VS Code extension names to skip during installation.
.PARAMETER Silent
Run in silent mode with minimal user interaction. Default is $false.
.PARAMETER Force
Force reinstall packages even if they're already installed. Default is $false.
.PARAMETER ConfigFile
Path to custom configuration JSON file. Default uses built-in configuration.
.PARAMETER LogLevel
Logging level: 'DEBUG', 'INFO', 'WARNING', 'ERROR'. Default is 'INFO'.
.EXAMPLE
.\setup-v1.ps1
Runs the complete development environment setup in full mode.
.EXAMPLE
.\setup-v1.ps1 -Mode Minimal -Silent
Runs minimal installation in silent mode.
.EXAMPLE
.\setup-v1.ps1 -SkipPackages "Docker Desktop,Node.js" -SkipExtensions "GitLens,Prettier"
Skips specific packages and extensions.
.EXAMPLE
.\setup-v1.ps1 -ConfigFile "C:\MyConfig\custom-config.json" -LogLevel DEBUG
Uses custom configuration file with debug logging.
.NOTES
Author: Christopher Alphonse
Last Updated: 2025-10-04
#>
param(
[ValidateSet('Full', 'Minimal', 'Custom', 'UpdateOnly')]
[string]$Mode = 'Full',
[string]$SkipPackages = '',
[string]$SkipExtensions = '',
[switch]$Silent = $false,
[switch]$Force = $false,
[string]$ConfigFile = '',
[ValidateSet('DEBUG', 'INFO', 'WARNING', 'ERROR')]
[string]$LogLevel = 'INFO',
[switch]$CheckUpdates = $true
)
$ErrorActionPreference = "Stop"
$ProgressPreference = "Continue"
# ===============================
# Version Information
# ===============================
$ScriptVersion = "2.0.0"
$ScriptName = "Development Environment Setup"
$GitHubRepo = "ChristopherAlphonse/dotfiles"
$GitHubRawBase = "https://raw.githubusercontent.com/$GitHubRepo/main"
# ===============================
# Update Management
# ===============================
function Test-ScriptUpdate {
Write-Host "`n🔍 Checking for script updates..." -ForegroundColor Cyan
Write-Log "INFO" "Checking for script updates from GitHub"
try {
$updateUrl = "$GitHubRawBase/setup-v1.ps1"
$response = Invoke-WebRequest -Uri $updateUrl -UseBasicParsing -TimeoutSec 10
$remoteContent = $response.Content
# Extract version from remote script
$versionMatch = [regex]::Match($remoteContent, '\$ScriptVersion = "([^"]+)"')
if ($versionMatch.Success) {
$remoteVersion = $versionMatch.Groups[1].Value
Write-Log "INFO" "Current version: $ScriptVersion, Remote version: $remoteVersion"
if ($remoteVersion -ne $ScriptVersion) {
Write-Host "📦 Update available!" -ForegroundColor Yellow
Write-Host " Current version: $ScriptVersion" -ForegroundColor White
Write-Host " Latest version: $remoteVersion" -ForegroundColor Green
Write-Log "INFO" "Update available: $ScriptVersion -> $remoteVersion"
return @{
Available = $true
CurrentVersion = $ScriptVersion
LatestVersion = $remoteVersion
UpdateUrl = $updateUrl
}
} else {
Write-Host "✅ Script is up to date (v$ScriptVersion)" -ForegroundColor Green
Write-Log "INFO" "Script is up to date"
return @{
Available = $false
CurrentVersion = $ScriptVersion
LatestVersion = $remoteVersion
}
}
} else {
Write-Host "⚠️ Could not determine remote version" -ForegroundColor Yellow
Write-Log "WARNING" "Could not extract version from remote script"
return @{
Available = $false
Error = "Could not determine remote version"
}
}
}
catch {
Write-Host "⚠️ Failed to check for updates: $_" -ForegroundColor Yellow
Write-Log "WARNING" "Failed to check for updates: $_"
return @{
Available = $false
Error = $_.Exception.Message
}
}
}
function Update-Script {
param(
[string]$UpdateUrl,
[string]$BackupPath = "$env:TEMP\setup-v1-backup.ps1"
)
Write-Host "`n🔄 Updating script..." -ForegroundColor Cyan
Write-Log "INFO" "Starting script update process"
try {
# Create backup of current script
$currentScriptPath = $MyInvocation.PSCommandPath
Copy-Item -Path $currentScriptPath -Destination $BackupPath -Force
Write-Host "📁 Backup created: $BackupPath" -ForegroundColor Green
Write-Log "INFO" "Backup created at: $BackupPath"
# Download updated script
Write-Host "📥 Downloading updated script..." -ForegroundColor Yellow
$updatedContent = Invoke-WebRequest -Uri $UpdateUrl -UseBasicParsing -TimeoutSec 30
$updatedContent.Content | Out-File -FilePath $currentScriptPath -Encoding UTF8 -Force
Write-Host "✅ Script updated successfully!" -ForegroundColor Green
Write-Log "INFO" "Script updated successfully"
return @{
Success = $true
BackupPath = $BackupPath
Message = "Script updated successfully. Backup saved to: $BackupPath"
}
}
catch {
Write-Host "❌ Failed to update script: $_" -ForegroundColor Red
Write-Log "ERROR" "Failed to update script: $_"
# Restore from backup if it exists
if (Test-Path $BackupPath) {
try {
Copy-Item -Path $BackupPath -Destination $currentScriptPath -Force
Write-Host "🔄 Restored from backup due to update failure" -ForegroundColor Yellow
Write-Log "INFO" "Restored script from backup due to update failure"
}
catch {
Write-Host "❌ Failed to restore from backup: $_" -ForegroundColor Red
Write-Log "ERROR" "Failed to restore from backup: $_"
}
}
return @{
Success = $false
Error = $_.Exception.Message
}
}
}
function Show-UpdatePrompt {
param(
[hashtable]$UpdateInfo
)
if (-not $UpdateInfo.Available) {
return $false
}
Write-Host "`n" -NoNewline
Write-Host "═" * 70 -ForegroundColor Yellow
Write-Host " Script Update Available" -ForegroundColor Yellow
Write-Host "═" * 70 -ForegroundColor Yellow
Write-Host "`nA newer version of the script is available:" -ForegroundColor White
Write-Host " Current: $($UpdateInfo.CurrentVersion)" -ForegroundColor Red
Write-Host " Latest: $($UpdateInfo.LatestVersion)" -ForegroundColor Green
Write-Host "`nWould you like to update now? (Y/N): " -NoNewline -ForegroundColor Yellow
$response = Read-Host
if ($response -eq 'Y' -or $response -eq 'y') {
$updateResult = Update-Script -UpdateUrl $UpdateInfo.UpdateUrl
if ($updateResult.Success) {
Write-Host "`n✅ $($updateResult.Message)" -ForegroundColor Green
Write-Host "Please restart the script to use the updated version." -ForegroundColor Cyan
Write-Log "INFO" "User chose to update script"
return $true
} else {
Write-Host "`n❌ Update failed: $($updateResult.Error)" -ForegroundColor Red
Write-Log "ERROR" "Script update failed: $($updateResult.Error)"
return $false
}
} else {
Write-Host "`n⏭️ Continuing with current version..." -ForegroundColor Yellow
Write-Log "INFO" "User chose not to update script"
return $false
}
}
function Update-Configurations {
Write-Host "`n🔄 Updating configurations..." -ForegroundColor Cyan
Write-Log "INFO" "Starting configuration update process"
try {
# Update dotfiles
Write-Host "📁 Updating dotfiles..." -ForegroundColor Yellow
$tempDir = Join-Path $env:TEMP "dotfiles-update-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
if (Test-Path $tempDir) {
Remove-Item -Path $tempDir -Recurse -Force
}
git clone $CONFIG.DotfilesRepo $tempDir
if ($LASTEXITCODE -eq 0) {
# Copy updated configurations
$sourcePath = Join-Path $tempDir "pwsh"
$destPath = $CONFIG.Paths.PowerShellConfig
if (Test-Path $sourcePath) {
Copy-Item -Path "$sourcePath\*" -Destination $destPath -Recurse -Force
Write-Host " ✅ PowerShell configurations updated" -ForegroundColor Green
}
# Update version information
Update-VersionInfo
# Clean up
Remove-Item -Path $tempDir -Recurse -Force
Write-Host "✅ Configurations updated successfully!" -ForegroundColor Green
Write-Log "INFO" "Configurations updated successfully"
return $true
} else {
Write-Host "❌ Failed to clone dotfiles repository" -ForegroundColor Red
Write-Log "ERROR" "Failed to clone dotfiles repository"
return $false
}
}
catch {
Write-Host "❌ Failed to update configurations: $_" -ForegroundColor Red
Write-Log "ERROR" "Failed to update configurations: $_"
return $false
}
}
function Update-VersionInfo {
$versionFile = Join-Path $CONFIG.Paths.PowerShellConfig "version.json"
$versionInfo = @{
scriptVersion = $ScriptVersion
lastUpdated = Get-Date -Format "yyyy-MM-dd"
configurationVersion = "1.0.0"
packagesVersion = "1.0.0"
extensionsVersion = "1.0.0"
dotfilesVersion = "1.0.0"
changelog = @(
@{
version = $ScriptVersion
date = Get-Date -Format "yyyy-MM-dd"
changes = @(
"Configuration updated via script",
"Last update: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
)
}
)
}
try {
$versionInfo | ConvertTo-Json -Depth 3 | Out-File -FilePath $versionFile -Encoding UTF8 -Force
Write-Host " ✅ Version information updated" -ForegroundColor Green
Write-Log "INFO" "Version information updated at: $versionFile"
}
catch {
Write-Host " ⚠️ Failed to update version information: $_" -ForegroundColor Yellow
Write-Log "WARNING" "Failed to update version information: $_"
}
}
function Get-VersionInfo {
$versionFile = Join-Path $CONFIG.Paths.PowerShellConfig "version.json"
if (Test-Path $versionFile) {
try {
$versionInfo = Get-Content $versionFile -Raw | ConvertFrom-Json
return $versionInfo
}
catch {
Write-Log "WARNING" "Failed to read version file: $_"
}
}
return $null
}
function Test-SetupAlreadyCompleted {
$stateFile = Join-Path $CONFIG.BackupDirectory "installation-state.json"
if (-not (Test-Path $stateFile)) {
return $false
}
try {
$state = Get-Content $stateFile -Raw | ConvertFrom-Json
return $state.Status -eq "Complete"
}
catch {
Write-Log "DEBUG" "Failed to read state file: $_"
return $false
}
}
function Show-IdempotencySummary {
param(
[array]$Results
)
$total = $Results.Count
$skipped = ($Results | Where-Object { $_.Skipped -eq $true }).Count
$updated = ($Results | Where-Object { $_.Success -eq $true -and $_.Skipped -ne $true }).Count
$failed = ($Results | Where-Object { $_.Success -eq $false }).Count
Write-Host "`n📊 Idempotency Summary:" -ForegroundColor Cyan
Write-Host " Total items processed: $total" -ForegroundColor White
Write-Host " Skipped (already up to date): $skipped" -ForegroundColor Yellow
Write-Host " Updated/Installed: $updated" -ForegroundColor Green
Write-Host " Failed: $failed" -ForegroundColor Red
if ($skipped -gt 0) {
Write-Host "`n✅ Script is idempotent - skipped $skipped items that were already up to date" -ForegroundColor Green
}
}
# ===============================
# Configuration Management
# ===============================
function Initialize-Configuration {
# Parse command-line parameters
$script:ScriptParams = @{
Mode = $Mode
SkipPackages = if ($SkipPackages) { $SkipPackages -split ',' | ForEach-Object { $_.Trim() } } else { @() }
SkipExtensions = if ($SkipExtensions) { $SkipExtensions -split ',' | ForEach-Object { $_.Trim() } } else { @() }
Silent = $Silent
Force = $Force
ConfigFile = $ConfigFile
LogLevel = $LogLevel
}
# Load custom configuration if provided
if ($script:ScriptParams.ConfigFile -and (Test-Path $script:ScriptParams.ConfigFile)) {
try {
$customConfig = Get-Content $script:ScriptParams.ConfigFile -Raw | ConvertFrom-Json
Write-Host "✅ Loaded custom configuration from: $($script:ScriptParams.ConfigFile)" -ForegroundColor Green
return $customConfig
}
catch {
Write-Host "⚠️ Failed to load custom configuration: $_" -ForegroundColor Yellow
Write-Host "Using default configuration instead." -ForegroundColor Yellow
}
}
return $null
}
function Get-InstallationMode {
param([string]$Mode)
switch ($Mode) {
'Minimal' {
return @{
Packages = @('Git', 'Visual Studio Code', 'PowerShell')
Extensions = @('ms-vscode.powershell', 'ms-vscode.vscode-json')
SkipDotfiles = $false
SkipVSCodeExtensions = $false
}
}
'Custom' {
return @{
Packages = $CONFIG.WingetPackages | Where-Object { $_.Name -notin $script:ScriptParams.SkipPackages }
Extensions = $CONFIG.VSCodeExtensions | Where-Object { $_.Name -notin $script:ScriptParams.SkipExtensions }
SkipDotfiles = $false
SkipVSCodeExtensions = $false
}
}
'UpdateOnly' {
return @{
Packages = @()
Extensions = @()
SkipDotfiles = $false
SkipVSCodeExtensions = $false
UpdateOnly = $true
}
}
default { # 'Full'
return @{
Packages = $CONFIG.WingetPackages
Extensions = $CONFIG.VSCodeExtensions
SkipDotfiles = $false
SkipVSCodeExtensions = $false
}
}
}
}
$CONFIG = @{
DotfilesRepo = "https://github.com/ChristopherAlphonse/dotfiles"
Paths = @{
Home = $env:USERPROFILE
Documents = [Environment]::GetFolderPath("MyDocuments")
LocalAppData = $env:LOCALAPPDATA
PowerShellConfig = "$([Environment]::GetFolderPath('MyDocuments'))\PowerShell"
VSCodeSettings = "$env:APPDATA\Code\User"
LogDirectory = "$env:TEMP\dev-setup-logs"
}
PackageManagement = @{
UseLatestVersions = $true
UpdateCheck = $true
ForceReinstall = $Force
SkipIfInstalled = -not $Force
}
WingetPackages = @(
@{
Id = "Git.Git";
Name = "Git";
RequiresRestart = $false;
Version = "latest";
Description = "Distributed version control system"
Category = "Development Tools"
},
@{
Id = "Microsoft.WindowsTerminal";
Name = "Windows Terminal";
RequiresRestart = $false;
Version = "latest";
Description = "Modern terminal application for Windows"
Category = "Terminal"
},
@{
Id = "Microsoft.VisualStudioCode";
Name = "VS Code";
RequiresRestart = $false;
Version = "latest";
Description = "Source code editor with built-in Git support"
Category = "Development Tools"
},
@{
Id = "Python.Python.3.11";
Name = "Python 3.11";
RequiresRestart = $false;
Version = "3.3";
Description = "Python programming language"
Category = "Programming Languages"
},
@{
Id = "Docker.DockerDesktop";
Name = "Docker Desktop";
RequiresRestart = $true;
Version = "latest";
Description = "Containerization platform"
Category = "Development Tools"
},
@{
Id = "SlackTechnologies.Slack";
Name = "Slack";
RequiresRestart = $false;
Version = "latest";
Description = "Team communication platform"
Category = "Communication"
},
@{
Id = "JanDeDobbeleer.OhMyPosh";
Name = "Oh My Posh";
RequiresRestart = $false;
Version = "latest";
Description = "Prompt theme engine for PowerShell"
Category = "Terminal"
},
@{
Id = "Microsoft.PowerToys";
Name = "PowerToys (Preview)";
RequiresRestart = $false;
Version = "latest";
Description = "Windows system utilities for power users"
Category = "System Tools"
}
)
RestartRequiredApps = @()
LogFile = ""
MaxLogSize = 10MB
MaxLogFiles = 5
StateFile = ""
BackupDirectory = ""
VSCodeExtensions = @(
@{ Id = "eamodio.gitlens"; Name = "GitLens" },
@{ Id = "esbenp.prettier-vscode"; Name = "Prettier" },
@{ Id = "ms-vscode.powershell"; Name = "PowerShell" },
@{ Id = "ms-vscode.vscode-json"; Name = "JSON" },
@{ Id = "ms-vscode.vscode-typescript-next"; Name = "TypeScript" },
@{ Id = "ms-vscode.vscode-eslint"; Name = "ESLint" },
@{ Id = "ms-vscode.remote-containers"; Name = "Dev Containers" },
@{ Id = "ms-vscode.remote-wsl"; Name = "WSL" },
@{ Id = "ms-vscode.vscode-github-actions"; Name = "GitHub Actions" },
@{ Id = "ms-vscode.vscode-markdown"; Name = "Markdown" }
)
}
function Write-Step {
param([string]$Message)
Write-Host "`n" -NoNewline
Write-Host "🔧 " -NoNewline -ForegroundColor Cyan
Write-Host "$Message" -ForegroundColor White
Write-Host "─" * 50 -ForegroundColor DarkCyan
}
function Write-Success {
param([string]$Message)
Write-Host "$Message" -ForegroundColor Green
}
function Write-Error {
param([string]$Message)
Write-Host "$Message" -ForegroundColor Red
}
# ===============================
# Logging System Functions
# ===============================
function Initialize-Logging {
Write-Host "Initializing logging system..." -ForegroundColor Cyan
if (-not (Test-Path $CONFIG.Paths.LogDirectory)) {
New-Item -ItemType Directory -Path $CONFIG.Paths.LogDirectory -Force | Out-Null
}
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$CONFIG.LogFile = Join-Path $CONFIG.Paths.LogDirectory "dev-setup-$timestamp.log"
Remove-OldLogs
Write-Log "INFO" "Development Environment Setup Started"
Write-Log "INFO" "Script Version: 2.0"
Write-Log "INFO" "PowerShell Version: $($PSVersionTable.PSVersion)"
Write-Log "INFO" "Windows Version: $([System.Environment]::OSVersion.VersionString)"
Write-Log "INFO" "User: $([System.Environment]::UserName)"
Write-Log "INFO" "Computer: $([System.Environment]::MachineName)"
Write-Log "INFO" "Log File: $($CONFIG.LogFile)"
}
function Write-Log {
param(
[Parameter(Mandatory = $true)]
[ValidateSet("INFO", "WARNING", "ERROR", "DEBUG")]
[string]$Level,
[Parameter(Mandatory = $true)]
[string]$Message,
[string]$Details = ""
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
if ($Details) {
$logEntry += " | Details: $Details"
}
try {
Add-Content -Path $CONFIG.LogFile -Value $logEntry -ErrorAction SilentlyContinue
}
catch {
Write-Host " Failed to write to log: $_" -ForegroundColor Yellow
}
if ($Level -eq "DEBUG") {
Write-Host "DEBUG: $Message" -ForegroundColor DarkGray
}
}
function Remove-OldLogs {
try {
$logFiles = Get-ChildItem -Path $CONFIG.Paths.LogDirectory -Filter "dev-setup-*.log" | Sort-Object LastWriteTime -Descending
if ($logFiles.Count -gt $CONFIG.MaxLogFiles) {
$filesToDelete = $logFiles | Select-Object -Skip $CONFIG.MaxLogFiles
foreach ($file in $filesToDelete) {
Remove-Item $file.FullName -Force
Write-Log "INFO" "Removed old log file: $($file.Name)"
}
}
}
catch {
Write-Log "WARNING" "Failed to clean up old logs: $_"
}
}
function Test-LogSize {
try {
if (Test-Path $CONFIG.LogFile) {
$logSize = (Get-Item $CONFIG.LogFile).Length
if ($logSize -gt $CONFIG.MaxLogSize) {
Write-Log "INFO" "Log file size exceeded limit, archiving..."
$archiveName = $CONFIG.LogFile -replace '\.log$', "-archive-$(Get-Date -Format 'yyyyMMdd-HHmmss').log"
Move-Item $CONFIG.LogFile $archiveName
Write-Log "INFO" "Log archived to: $archiveName"
}
}
}
catch {
Write-Log "WARNING" "Failed to check log size: $_"
}
}
# ===============================
# Rollback System Functions
# ===============================
function Initialize-RollbackSystem {
Write-Log "INFO" "Initializing rollback system"
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$CONFIG.BackupDirectory = Join-Path $env:TEMP "dev-setup-backup-$timestamp"
$CONFIG.StateFile = Join-Path $CONFIG.BackupDirectory "installation-state.json"
if (-not (Test-Path $CONFIG.BackupDirectory)) {
New-Item -ItemType Directory -Path $CONFIG.BackupDirectory -Force | Out-Null
Write-Log "DEBUG" "Created backup directory: $($CONFIG.BackupDirectory)"
}
$initialState = @{
StartTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
InstalledPackages = @()
CopiedFiles = @()
CreatedDirectories = @()
Status = "InProgress"
}
$initialState | ConvertTo-Json -Depth 3 | Out-File -FilePath $CONFIG.StateFile -Encoding UTF8
Write-Log "INFO" "Rollback system initialized"
}
function Backup-ExistingConfigs {
Write-Log "INFO" "Backing up existing configuration files"
$backupResults = @{
PowerShellProfile = $false
PowerShellConfig = $false
TerminalSettings = $false
VSCodeSettings = $false
GitConfig = $false
}
try {
$profilePath = "$($CONFIG.Paths.PowerShellConfig)/Microsoft.PowerShell_profile.ps1"
if (Test-Path $profilePath) {
$backupPath = Join-Path $CONFIG.BackupDirectory "Microsoft.PowerShell_profile.ps1.backup"
Copy-Item $profilePath $backupPath -Force
$backupResults.PowerShellProfile = $true
Write-Log "DEBUG" "Backed up PowerShell profile"
}
$configPath = "$($CONFIG.Paths.PowerShellConfig)/powershell.config.json"
if (Test-Path $configPath) {
$backupPath = Join-Path $CONFIG.BackupDirectory "powershell.config.json.backup"
Copy-Item $configPath $backupPath -Force
$backupResults.PowerShellConfig = $true
Write-Log "DEBUG" "Backed up PowerShell config"
}
$terminalPath = "$($CONFIG.Paths.LocalAppData)\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json"
if (Test-Path $terminalPath) {
$backupPath = Join-Path $CONFIG.BackupDirectory "terminal-settings.json.backup"
Copy-Item $terminalPath $backupPath -Force
$backupResults.TerminalSettings = $true
Write-Log "DEBUG" "Backed up Terminal settings"
}
$vscodePath = "$($CONFIG.Paths.VSCodeSettings)/custom-vscode.css"
if (Test-Path $vscodePath) {
$backupPath = Join-Path $CONFIG.BackupDirectory "custom-vscode.css.backup"
Copy-Item $vscodePath $backupPath -Force
$backupResults.VSCodeSettings = $true
Write-Log "DEBUG" "Backed up VS Code settings"
}
$gitPath = "$($CONFIG.Paths.Home)/.gitconfig"
if (Test-Path $gitPath) {
$backupPath = Join-Path $CONFIG.BackupDirectory ".gitconfig.backup"
Copy-Item $gitPath $backupPath -Force
$backupResults.GitConfig = $true
Write-Log "DEBUG" "Backed up Git config"
}
Write-Log "INFO" "Configuration backup completed"
return $backupResults
}
catch {
Write-Log "ERROR" "Failed to backup existing configs" "Exception: $($_.Exception.Message)"
return $backupResults
}
}
function Update-InstallationState {
param(
[string]$Operation,
[hashtable]$Data
)
try {
if (Test-Path $CONFIG.StateFile) {
$state = Get-Content $CONFIG.StateFile -Raw | ConvertFrom-Json
switch ($Operation) {
"PackageInstalled" {
$state.InstalledPackages += $Data
Write-Log "DEBUG" "Updated state: Package installed - $($Data.Name)"
}
"FileCopied" {
$state.CopiedFiles += $Data
Write-Log "DEBUG" "Updated state: File copied - $($Data.Destination)"
}
"DirectoryCreated" {
$state.CreatedDirectories += $Data
Write-Log "DEBUG" "Updated state: Directory created - $($Data.Path)"
}
"StatusComplete" {
$state.Status = "Complete"
$state.EndTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Log "INFO" "Updated state: Installation completed"
}
"StatusFailed" {
$state.Status = "Failed"
$state.EndTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$state.ErrorMessage = $Data.ErrorMessage
Write-Log "INFO" "Updated state: Installation failed"
}
}
$state | ConvertTo-Json -Depth 3 | Out-File -FilePath $CONFIG.StateFile -Encoding UTF8
}
}
catch {
Write-Log "WARNING" "Failed to update installation state: $_"
}
}
function Invoke-Rollback {
Write-Host "`n🔄 Starting rollback process..." -ForegroundColor Yellow
Write-Log "INFO" "Starting rollback process"
try {
if (-not (Test-Path $CONFIG.StateFile)) {
Write-Host "❌ No installation state found. Cannot perform rollback." -ForegroundColor Red
Write-Log "ERROR" "No installation state found for rollback"
return $false
}
$state = Get-Content $CONFIG.StateFile -Raw | ConvertFrom-Json
Write-Log "INFO" "Loaded installation state with $($state.InstalledPackages.Count) packages and $($state.CopiedFiles.Count) files"
# Uninstall packages
if ($state.InstalledPackages.Count -gt 0) {
Write-Host "📦 Uninstalling packages..." -ForegroundColor Cyan
foreach ($package in $state.InstalledPackages) {
try {
Write-Host " Removing $($package.Name)..." -ForegroundColor Yellow
$result = Start-Process -FilePath "winget" -ArgumentList "uninstall --id $($package.Id) --silent" -Wait -PassThru -NoNewWindow
if ($result.ExitCode -eq 0) {
Write-Host " ✅ Removed $($package.Name)" -ForegroundColor Green
Write-Log "INFO" "Successfully uninstalled: $($package.Name)"
} else {
Write-Host " ⚠️ Failed to remove $($package.Name)" -ForegroundColor Yellow
Write-Log "WARNING" "Failed to uninstall: $($package.Name)"
}
}
catch {
Write-Host " ❌ Error removing $($package.Name): $_" -ForegroundColor Red
Write-Log "ERROR" "Error uninstalling $($package.Name): $_"
}
}
}
# Restore backed-up files
if ($state.CopiedFiles.Count -gt 0) {
Write-Host "📁 Restoring configuration files..." -ForegroundColor Cyan
foreach ($file in $state.CopiedFiles) {
try {
$backupPath = Join-Path $CONFIG.BackupDirectory "$(Split-Path -Leaf $file.Destination).backup"
if (Test-Path $backupPath) {
Copy-Item $backupPath $file.Destination -Force
Write-Host " ✅ Restored $($file.Destination)" -ForegroundColor Green
Write-Log "INFO" "Restored file: $($file.Destination)"
} else {
# If no backup, remove the file
if (Test-Path $file.Destination) {
Remove-Item $file.Destination -Force
Write-Host " 🗑️ Removed $($file.Destination)" -ForegroundColor Yellow
Write-Log "INFO" "Removed file (no backup): $($file.Destination)"
}
}
}
catch {
Write-Host " ❌ Error restoring $($file.Destination): $_" -ForegroundColor Red
Write-Log "ERROR" "Error restoring $($file.Destination): $_"
}
}
}
# Remove created directories
if ($state.CreatedDirectories.Count -gt 0) {
Write-Host "📂 Cleaning up created directories..." -ForegroundColor Cyan
foreach ($dir in $state.CreatedDirectories) {
try {
if (Test-Path $dir.Path) {
Remove-Item $dir.Path -Recurse -Force
Write-Host " 🗑️ Removed $($dir.Path)" -ForegroundColor Yellow
Write-Log "INFO" "Removed directory: $($dir.Path)"
}
}
catch {
Write-Host " ❌ Error removing $($dir.Path): $_" -ForegroundColor Red
Write-Log "ERROR" "Error removing directory $($dir.Path): $_"
}
}
}
Write-Host "`n✅ Rollback completed!" -ForegroundColor Green
Write-Log "INFO" "Rollback process completed successfully"
return $true
}
catch {
Write-Host "`n❌ Rollback failed: $_" -ForegroundColor Red
Write-Log "ERROR" "Rollback process failed" "Exception: $($_.Exception.Message)"
return $false
}
}
function Show-RollbackPrompt {
Write-Host "`n" -NoNewline
Write-Host "═" * 60 -ForegroundColor Red
Write-Host " Installation Failed" -ForegroundColor Red
Write-Host "═" * 60 -ForegroundColor Red
Write-Host "`nWould you like to rollback all changes? (Y/N): " -NoNewline -ForegroundColor Yellow
$response = Read-Host
if ($response -eq 'Y' -or $response -eq 'y') {
Write-Log "INFO" "User chose to rollback changes"
return Invoke-Rollback
} else {
Write-Log "INFO" "User chose not to rollback changes"
Write-Host "`n⚠️ Changes will remain on your system." -ForegroundColor Yellow
Write-Host "You can manually rollback using the state file: $($CONFIG.StateFile)" -ForegroundColor Cyan
return $false
}
}
# ===============================
# VS Code Extension Functions
# ===============================
function Test-VSCodeInstalled {
try {
$codeVersion = & code --version 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Log "DEBUG" "VS Code is installed: $($codeVersion[0])"
return $true
}
}
catch {
Write-Log "DEBUG" "VS Code not found in PATH"
}
return $false
}
function Install-VSCodeExtensions {
Write-Host "`n📦 Installing VS Code extensions..." -ForegroundColor Cyan
Write-Log "INFO" "Starting VS Code extension installation"
if (-not (Test-VSCodeInstalled)) {
Write-Host "⚠️ VS Code is not installed or not in PATH. Skipping extension installation." -ForegroundColor Yellow
Write-Log "WARNING" "VS Code not found, skipping extension installation"
return $false
}
# Get extensions based on installation mode
$extensionsToInstall = Get-InstallationMode -Mode $script:ScriptParams.Mode
$extensions = $extensionsToInstall.Extensions
$installedExtensions = @()
$failedExtensions = @()
Write-Host "Installing $($extensions.Count) extensions..." -ForegroundColor White
foreach ($extension in $extensions) {
try {
Write-Host " Installing $($extension.Name)..." -ForegroundColor Yellow
Write-Log "DEBUG" "Installing VS Code extension: $($extension.Name) ($($extension.Id))"
$result = Start-Process -FilePath "code" -ArgumentList "--install-extension", $extension.Id, "--force" -Wait -PassThru -NoNewWindow
if ($result.ExitCode -eq 0) {
Write-Host " ✅ Installed $($extension.Name)" -ForegroundColor Green
$installedExtensions += $extension
Write-Log "INFO" "Successfully installed VS Code extension: $($extension.Name)"
# Update installation state
Update-InstallationState -Operation "FileCopied" -Data @{
Source = "VS Code Marketplace"
Destination = "VS Code Extension: $($extension.Name)"
Description = "VS Code Extension: $($extension.Name)"
CopyTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}
} else {
Write-Host " ❌ Failed to install $($extension.Name)" -ForegroundColor Red
$failedExtensions += $extension
Write-Log "WARNING" "Failed to install VS Code extension: $($extension.Name)"
}
}
catch {
Write-Host " ❌ Error installing $($extension.Name): $_" -ForegroundColor Red
$failedExtensions += $extension
Write-Log "ERROR" "Error installing VS Code extension $($extension.Name): $_"
}
}
# Summary
Write-Host "`n📊 VS Code Extensions Summary:" -ForegroundColor Cyan
Write-Host " ✅ Installed: $($installedExtensions.Count)/$($CONFIG.VSCodeExtensions.Count)" -ForegroundColor Green
if ($failedExtensions.Count -gt 0) {
Write-Host " ❌ Failed:" -ForegroundColor Red
$failedExtensions | ForEach-Object { Write-Host " - $($_.Name)" -ForegroundColor Yellow }
Write-Log "WARNING" "Failed to install $($failedExtensions.Count) VS Code extensions"
}
Write-Log "INFO" "VS Code extension installation completed: $($installedExtensions.Count)/$($CONFIG.VSCodeExtensions.Count) successful"
return $installedExtensions.Count -gt 0
}
function Test-VSCodeExtensions {
Write-Host "`n🔍 Verifying VS Code extensions..." -ForegroundColor Cyan
Write-Log "INFO" "Verifying installed VS Code extensions"
if (-not (Test-VSCodeInstalled)) {
Write-Host "⚠️ VS Code is not available for verification." -ForegroundColor Yellow
return $false
}