-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ps1
More file actions
2390 lines (2133 loc) · 90.6 KB
/
Copy pathinstall.ps1
File metadata and controls
2390 lines (2133 loc) · 90.6 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
Cross-platform dotfiles installer for native Windows.
.DESCRIPTION
Manages dotfiles restore, backup, and scheduled backups using winget
and PowerShell symlinks. This is the Windows-native counterpart to
install.sh (which covers macOS, Linux, and WSL).
.PARAMETER Command
The action to perform: restore, backup, or schedule.
.PARAMETER DryRun
Run in dry-run mode without making any changes.
.EXAMPLE
.\install.ps1 restore
.\install.ps1 backup -DryRun
.\install.ps1 schedule
#>
param(
[Parameter(Position = 0)]
[string]$Command,
[Alias("d")]
[switch]$DryRun,
[Alias("h")]
[switch]$Help
)
# --- Configuration ---
$ESC = [char]27
$NC = "$($ESC)[0m"
$C_LAVENDER = "$($ESC)[38;2;180;190;254m"
$C_BLUE = "$($ESC)[38;2;137;180;250m"
$C_PEACH = "$($ESC)[38;2;250;179;135m"
# Enable ANSI colors for Windows PowerShell (5.1)
if ($PSVersionTable.PSVersion.Major -le 5) {
try {
$Signature = @'
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
'@
$null = Add-Type -MemberDefinition $Signature -Name "Win32" -Namespace "Win32" -ErrorAction SilentlyContinue
$handle = [Win32.Win32]::GetStdHandle(-11) # STDOUT
$mode = 0
if ([Win32.Win32]::GetConsoleMode($handle, [ref]$mode)) {
$null = [Win32.Win32]::SetConsoleMode($handle, $mode -bor 4)
}
} catch { }
}
$ValidCommands = @("restore", "backup", "schedule", "help")
if ($Command -and $Command -notin $ValidCommands) {
Write-Host "${C_PEACH}X Invalid command: $Command. Valid commands are: $($ValidCommands -join ', ')${NC}"
exit 1
}
# --- Admin Gate ---
# Require elevation upfront for any command that changes system state.
# Developer Mode, wsl --install, and some winget packages all need admin;
# a single early check produces one clear message instead of per-step
# warnings mid-run. Skipped for help/dry-run since those don't mutate.
$needsAdmin = if ($Command) { $Command -in @("restore", "backup", "schedule") } else { $true }
if ($needsAdmin -and -not $Help -and -not $DryRun) {
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "${C_PEACH}X This script must be run from an Administrator PowerShell.${NC}"
Write-Host "${C_YELLOW}! Right-click 'Windows Terminal' (or 'PowerShell') and pick 'Run as Administrator', then re-run:${NC}"
return
}
}
$DotfilesDir = Join-Path $env:USERPROFILE "dotfiles"
$DotfilesRepo = "ssh://git@github.com:rdruker_tps/dotfiles.git"
# Force wsl.exe to emit UTF-8 instead of UTF-16 LE. Without this, commands
# like `wsl --list --quiet` return strings riddled with NUL bytes that break
# regex/string comparisons in PowerShell.
$env:WSL_UTF8 = "1"
# --- Bootstrap ---
# When invoked remotely (irm ... | iex), $MyInvocation.MyCommand.Definition
# will not point to a file inside the repo. Detect this and bootstrap.
function Test-IsLocal {
$scriptPath = $MyInvocation.ScriptName
if (-not $scriptPath) { return $false }
$parentDir = Split-Path -Parent $scriptPath
return (Test-Path (Join-Path $parentDir ".git"))
}
function Wait-ForExit {
<#
.SYNOPSIS
Pauses so the user can read output before the window closes.
Falls back to Read-Host when the host doesn't support RawUI.ReadKey
(e.g., ISE, VS Code integrated terminal).
#>
param([string]$Message = "Press Enter to close...")
Write-Host ""
Write-Host $Message
try {
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
catch {
$null = Read-Host
}
}
function Invoke-Bootstrap {
<#
.SYNOPSIS
Installs git via winget, clones the repo, and re-executes locally.
.NOTES
Uses `return` instead of `exit` throughout. When this script is run
via `irm ... | iex`, calling `exit` terminates the user's interactive
PowerShell session (closing the terminal window). Returning instead
just stops the bootstrap scriptblock and leaves the session alive.
#>
Write-Host "${C_BLUE}=== Bootstrapping dotfiles ===${NC}"
# Ensure winget is available
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
Write-Host "${C_PEACH}X winget not found. Please install App Installer from the Microsoft Store.${NC}"
return
}
# Install git if missing
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
Write-Host "Installing git..."
winget install --id Git.Git --accept-package-agreements --accept-source-agreements --silent
# Refresh PATH so git is available in this session
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
}
# Clone or pull
if (Test-Path (Join-Path $DotfilesDir ".git")) {
Write-Host "Dotfiles repo already exists. Pulling latest changes..."
git -C $DotfilesDir pull origin main
if ($LASTEXITCODE -ne 0) {
Write-Host "${C_PEACH}X Failed to pull latest changes.${NC}"
return
}
}
else {
Write-Host "Cloning dotfiles repo..."
git clone $DotfilesRepo $DotfilesDir
if ($LASTEXITCODE -ne 0) {
Write-Host "${C_PEACH}X Failed to clone dotfiles repo.${NC}"
# Attempt to fix partial clone/checkout if it failed due to paths (e.g. symlinks)
if (Test-Path $DotfilesDir) {
Write-Host "Attempting to restore checkout..."
git -C $DotfilesDir restore --source=HEAD :/
}
if (-not (Test-Path (Join-Path $DotfilesDir "install.ps1"))) {
Write-Host "${C_PEACH}X Bootstrap failed: Repo cloned but checkout is incomplete.${NC}"
return
}
}
}
# Re-execute from the cloned repo
$localScript = Join-Path $DotfilesDir "install.ps1"
if (-not (Test-Path $localScript)) {
Write-Host "${C_PEACH}X Could not find local install.ps1 at $localScript. Bootstrap failed.${NC}"
return
}
Write-Host "Handing off to local install.ps1..."
$effectiveCommand = if ($Command) { $Command } else { "restore" }
# Try pwsh first, then powershell.exe
$exe = if (Get-Command pwsh -ErrorAction SilentlyContinue) { "pwsh" } else { "powershell.exe" }
# Use -File to avoid ampersand parser issues. -ExecutionPolicy Bypass ensures it runs.
if ($exe -eq "pwsh") {
pwsh -NoProfile -ExecutionPolicy Bypass -File "$localScript" $effectiveCommand
}
else {
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$localScript" $effectiveCommand
}
$childExit = $LASTEXITCODE
if ($childExit -ne 0) {
Write-Host "${C_PEACH}X Local execution failed with exit code $childExit.${NC}"
}
# Intentionally no `exit` here -- returning normally keeps the caller's
# interactive session (and its terminal window) open.
}
if (-not (Test-IsLocal)) {
try {
Invoke-Bootstrap
}
catch {
Write-Host "${C_PEACH}X A bootstrap error occurred: $($_.Exception.Message)${NC}"
}
# Stop here -- the rest of this file expects to run from a cloned repo
# on disk, which is not the case when invoked via `irm | iex`.
# `return` at script scope ends the iex scriptblock without closing
# the user's PowerShell session.
return
}
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$WingetPackagesFile = Join-Path $ScriptDir ".config\winget-packages.txt"
$ScoopBucketsFile = Join-Path $ScriptDir ".config\scoop-buckets.txt"
$ScoopPackagesFile = Join-Path $ScriptDir ".config\scoop-packages.txt"
$NpmGlobalFile = Join-Path $ScriptDir ".config\npm-global-packages.txt"
$PipxPackagesFile = Join-Path $ScriptDir ".config\pipx-packages.txt"
$BunPackagesFile = Join-Path $ScriptDir ".config\bun-packages.txt"
$PersonalizationRegFile = Join-Path $ScriptDir ".config\windows-personalization.reg"
$StartupRegFile = Join-Path $ScriptDir ".config\windows-startup.reg"
$StartupFolderDir = Join-Path $ScriptDir ".config\windows-startup"
$WindowsTerminalConfigDir = Join-Path $ScriptDir ".config\windows-terminal"
$WindowsTerminalLocalState = Join-Path $env:LOCALAPPDATA "Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState"
$WarpConfigDir = Join-Path $ScriptDir ".warp"
$WarpLocalState = Join-Path $env:LOCALAPPDATA "warp\Warp\config"
$QtCreatorConfigDir = Join-Path $ScriptDir ".config\qtcreator"
$QtCreatorLocalState = Join-Path $env:APPDATA "QtProject\qtcreator"
$WallpapersDir = Join-Path $ScriptDir ".wallpapers"
$DotfilesTarget = $env:USERPROFILE
# --- Colors (ANSI escape sequences) ---
$C_SAPPHIRE = "$($ESC)[38;2;116;199;236m"
$C_SKY = "$($ESC)[38;2;137;220;235m"
$C_TEAL = "$($ESC)[38;2;148;226;213m"
$C_GREEN = "$($ESC)[38;2;166;227;161m"
$C_YELLOW = "$($ESC)[38;2;249;226;175m"
# --- Logo ---
function Print-Logo {
Write-Host "${C_LAVENDER} ____ _ __ _ _ ${NC}"
Write-Host "${C_BLUE}| _ \ ___ | |_ / _(_) | ___ ___ ${NC}"
Write-Host "${C_SAPPHIRE}| | | |/ _ \| __| |_| | |/ _ \/ __|${NC}"
Write-Host "${C_SKY}| |_| | (_) | |_| _| | | __/\__ \ ${NC}"
Write-Host "${C_TEAL}|____/ \___/ \__|_| |_|_|\___||___/${NC}"
Write-Host ""
}
# --- Utility Functions ---
function Print-Header {
param([string]$Message)
Write-Host "${C_BLUE}=================================================${NC}"
Write-Host "${C_LAVENDER} $Message ${NC}"
Write-Host "${C_BLUE}=================================================${NC}"
}
function Print-Success {
param([string]$Message)
Write-Host "${C_GREEN}+ $Message${NC}"
}
function Print-Warning {
param([string]$Message)
Write-Host "${C_YELLOW}! $Message${NC}"
}
function Print-Error {
param([string]$Message)
Write-Host "${C_PEACH}X $Message${NC}"
}
function Print-Help {
Print-Logo
Write-Host 'Usage: .\install.ps1 <command> [options]'
Write-Host ""
Write-Host "Commands:"
Write-Host " restore Restore dotfiles and install dependencies"
Write-Host " backup Update package lists with current setup"
Write-Host " schedule Schedule hourly backups using Task Scheduler"
Write-Host ""
Write-Host "Options:"
Write-Host " -Help, -h Show this help message and exit"
Write-Host " -DryRun, -d Run in dry-run mode (no changes will be made)"
}
function Run-Command {
<#
.SYNOPSIS
Executes a command or prints it in dry-run mode.
#>
param([string]$Cmd)
if ($DryRun) {
Write-Host "${C_YELLOW}`[DRY RUN`] Would execute: $Cmd${NC}"
}
else {
Invoke-Expression $Cmd
}
}
# --- Symlink Creation (stow alternative) ---
function Get-StowIgnorePatterns {
<#
.SYNOPSIS
Parses .stowrc at the repo root and returns user-supplied ignore
regex patterns.
.DESCRIPTION
Each `--ignore=<regex>` line contributes one pattern. Blank lines and
comments (`#`) are skipped. Matches GNU Stow's semantics: each pattern
is a regex matched against a path's basename.
#>
$stowrc = Join-Path $ScriptDir ".stowrc"
if (-not (Test-Path $stowrc)) { return @() }
$patterns = @()
foreach ($line in Get-Content $stowrc) {
$trimmed = $line.Trim()
if (-not $trimmed -or $trimmed.StartsWith('#')) { continue }
if ($trimmed -match '^--ignore=(.+)$') {
$patterns += $matches[1].Trim()
}
}
return $patterns
}
function Create-Symlinks {
<#
.SYNOPSIS
Creates symlinks from the dotfiles directory into the user's home,
mirroring what GNU Stow does on Unix systems.
#>
Print-Header "Creating symlinks..."
# Windows privilege strategy:
# - Directories -> Junction (no admin, no Developer Mode required)
# - Files -> HardLink (no admin required on NTFS)
# SymbolicLink is avoided because it requires admin OR Developer Mode on Windows.
#
# Layout strategy (mirrors stow on Unix):
# - .config/* is expanded per-child so ~/.config can coexist with non-repo tools
# - All other top-level directories are junctioned whole into $HOME
# - Top-level files are hardlinked into $HOME
# Ignore list has two layers, mirroring GNU Stow:
# 1. Built-in defaults: VCS metadata + README/LICENSE (stow always
# ignores these regardless of .stowrc).
# 2. User patterns from .stowrc (each `--ignore=<regex>` line). Stow
# treats each ignore entry as a regex matched against the basename.
$builtinIgnoreRegex = @(
'^\.git$', '^\.gitignore$', '^\.gitmodules$',
'^RCS$', '^CVS$', '^\.svn$', '^_darcs$', '^\.hg$',
'^README.*', '^LICENSE.*', '^COPYING$',
'^\.DS_Store$'
)
$userIgnoreRegex = Get-StowIgnorePatterns
$allIgnoreRegex = $builtinIgnoreRegex + $userIgnoreRegex
function Test-IsIgnored([string]$name) {
foreach ($pat in $allIgnoreRegex) {
if ($name -match $pat) { return $true }
}
return $false
}
# Helper: create a junction at $dest pointing to $src.
function New-JunctionLink($dest, $src, $label) {
if (Test-Path -LiteralPath $dest) {
Print-Warning "Already exists, skipping: $dest"
$script:skipped++
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would link: $dest -> $src"
return
}
try {
$escDest = [Management.Automation.WildcardPattern]::Escape($dest)
$escSrc = [Management.Automation.WildcardPattern]::Escape($src)
New-Item -ItemType Junction -Path $escDest -Target $escSrc -ErrorAction Stop | Out-Null
Print-Success "Linked: $dest -> $src"
$script:linked++
}
catch {
Print-Error "Failed to link ${label}: $($_.Exception.Message)"
$script:failed++
}
}
# Helper: create a hardlink at $dest pointing to $src.
function New-FileLink($dest, $src, $label) {
if (Test-Path -LiteralPath $dest) {
Print-Warning "Already exists, skipping: $dest"
$script:skipped++
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would link: $dest -> $src"
return
}
try {
$escDest = [Management.Automation.WildcardPattern]::Escape($dest)
$escSrc = [Management.Automation.WildcardPattern]::Escape($src)
New-Item -ItemType HardLink -Path $escDest -Target $escSrc -ErrorAction Stop | Out-Null
Print-Success "Linked: $dest -> $src"
$script:linked++
}
catch {
Print-Error "Failed to link ${label}: $($_.Exception.Message)"
$script:failed++
}
}
$script:linked = 0
$script:skipped = 0
$script:failed = 0
$topLevel = Get-ChildItem -Path $ScriptDir -Force | Where-Object { -not (Test-IsIgnored $_.Name) }
$configTarget = Join-Path $DotfilesTarget ".config"
if (Test-Path -LiteralPath $configTarget) {
$configItem = Get-Item -LiteralPath $configTarget -Force -ErrorAction SilentlyContinue
if ($configItem -and -not $configItem.LinkType) {
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would remove existing directory to replace with symlink: $configTarget"
}
else {
Print-Warning "Removing existing directory to replace with symlink: $configTarget"
Remove-Item -Path $configTarget -Recurse -Force
}
}
}
foreach ($item in $topLevel) {
if ($item.PSIsContainer) {
# Top-level directory: junction whole thing into $HOME
New-JunctionLink (Join-Path $DotfilesTarget $item.Name) $item.FullName $item.Name
}
else {
# Top-level file: hardlink into $HOME
New-FileLink (Join-Path $DotfilesTarget $item.Name) $item.FullName $item.Name
}
}
Print-Success "Symlinks: $($script:linked) linked, $($script:skipped) skipped, $($script:failed) failed."
if ($script:failed -gt 0) {
throw "Symlink creation had $($script:failed) failure(s)."
}
}
function Link-QtCreatorFolder {
<#
.SYNOPSIS
Creates a junction from %APPDATA%\QtProject\qtcreator to the dotfiles
repo's .config\qtcreator directory. Used during restore so Qt Creator
settings are managed directly from the repo.
.DESCRIPTION
Replaces any existing qtcreator folder at the target with a junction
pointing back to the repo. Since the repo owns the files, no separate
backup step is needed -- edits in Qt Creator write through the
junction into the repo working tree.
#>
Print-Header "Linking Qt Creator configuration..."
$src = $QtCreatorConfigDir
$dest = $QtCreatorLocalState
if (-not (Test-Path $src)) {
Print-Warning "Qt Creator config not found in dotfiles repo ($src). Skipping."
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would junction $dest -> $src"
return
}
try {
# Ensure parent directory exists
$parent = Split-Path -Parent $dest
if (-not (Test-Path $parent)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
# Remove existing target (junction, symlink, or real directory)
if (Test-Path -LiteralPath $dest) {
$item = Get-Item -LiteralPath $dest -Force -ErrorAction SilentlyContinue
if ($item.LinkType) {
Print-Warning "Already linked, skipping: $dest"
return
}
else {
Remove-Item -Path $dest -Recurse -Force
Print-Warning "Removed existing directory: $dest"
}
}
$escDest = [Management.Automation.WildcardPattern]::Escape($dest)
$escSrc = [Management.Automation.WildcardPattern]::Escape($src)
New-Item -ItemType Junction -Path $escDest -Target $escSrc -ErrorAction Stop | Out-Null
Print-Success "Linked: $dest -> $src"
}
catch {
Print-Error "Failed to link Qt Creator config: $($_.Exception.Message)"
}
}
function Test-IsAdmin {
<#
.SYNOPSIS
Returns $true if the current session is elevated (Administrator).
#>
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Enable-DeveloperMode {
<#
.SYNOPSIS
Enables Windows Developer Mode by setting the AppModelUnlock flag in
HKLM. Developer Mode lets non-admin users create SymbolicLinks and
enables sideloading; it's a one-time, machine-scope flip.
#>
Print-Header "Enabling Windows Developer Mode..."
$regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
$valueName = "AllowDevelopmentWithoutDevLicense"
$current = Get-ItemProperty -Path $regPath -Name $valueName -ErrorAction SilentlyContinue
if ($current -and $current.$valueName -eq 1) {
Print-Success "Developer Mode is already enabled."
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would set $regPath\$valueName = 1 (enables Developer Mode)."
return
}
try {
if (-not (Test-Path $regPath)) {
New-Item -Path $regPath -Force -ErrorAction Stop | Out-Null
}
New-ItemProperty -Path $regPath -Name $valueName -PropertyType DWord -Value 1 -Force -ErrorAction Stop | Out-Null
Print-Success "Developer Mode enabled."
}
catch {
Print-Error "Failed to enable Developer Mode: $($_.Exception.Message)"
}
}
function Configure-GitDefaults {
<#
.SYNOPSIS
Configures global git defaults: LF line endings and long path support.
.DESCRIPTION
Sets core.autocrlf=input so CRLF is converted to LF on commit but
checkout leaves files as-is, core.eol=lf so new files use Unix
line endings, and core.fileMode=false so permission differences
between Unix (755) and Windows (644) are ignored. These are global
(--global) settings so they apply to every repo on the machine.
#>
Print-Header "Configuring git defaults..."
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
Print-Warning "git not found. Skipping git configuration."
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would set git config --global core.autocrlf input"
Print-Warning "`[DRY RUN`] Would set git config --global core.eol lf"
Print-Warning "`[DRY RUN`] Would set git config --global core.fileMode false"
return
}
try {
git config --global core.autocrlf input
git config --global core.eol lf
git config --global core.fileMode false
Print-Success "Git configured: core.autocrlf=input, core.eol=lf, core.fileMode=false."
}
catch {
Print-Error "Failed to configure git defaults: $($_.Exception.Message)"
}
}
function Enable-LongPaths {
<#
.SYNOPSIS
Enables long path support in Windows by setting the LongPathsEnabled flag.
#>
Print-Header "Enabling Long Path Support..."
$regPath = "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem"
$valueName = "LongPathsEnabled"
$current = Get-ItemProperty -Path $regPath -Name $valueName -ErrorAction SilentlyContinue
if ($current -and $current.$valueName -eq 1) {
Print-Success "Long Path support is already enabled."
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would set $regPath\$valueName = 1 (enables Long Paths)."
return
}
try {
if (-not (Test-Path $regPath)) {
New-Item -Path $regPath -Force -ErrorAction Stop | Out-Null
}
New-ItemProperty -Path $regPath -Name $valueName -PropertyType DWord -Value 1 -Force -ErrorAction Stop | Out-Null
Print-Success "Long Path support enabled."
}
catch {
Print-Error "Failed to enable Long Path support: $($_.Exception.Message)"
}
}
# --- Fonts ---
function Install-Fonts {
<#
.SYNOPSIS
Installs all fonts from .config\fonts and applies the SF Pro Display registry tweak.
#>
Print-Header "Installing fonts..."
$fontsDir = Join-Path $ScriptDir ".config\fonts"
if (-not (Test-Path $fontsDir)) {
Print-Warning "Fonts directory not found: $fontsDir. Skipping."
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would install fonts from $fontsDir"
Print-Warning "`[DRY RUN`] Would apply font registry tweaks."
return
}
try {
$fontFiles = Get-ChildItem -Path $fontsDir -Include *.ttf,*.otf -Recurse -File
$systemFontsDir = [Environment]::GetFolderPath('Fonts')
$regKey = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
$installed = 0
foreach ($font in $fontFiles) {
$destPath = Join-Path $systemFontsDir $font.Name
if (-not (Test-Path -LiteralPath $destPath)) {
Copy-Item -LiteralPath $font.FullName -Destination $destPath -Force
$fontName = $font.BaseName
if ($font.Extension -match '\.ttf') { $fontName += " (TrueType)" }
elseif ($font.Extension -match '\.otf') { $fontName += " (OpenType)" }
New-ItemProperty -Path $regKey -Name $fontName -Value $font.Name -PropertyType String -Force -ErrorAction SilentlyContinue | Out-Null
$installed++
}
}
if ($installed -gt 0) {
Print-Success "Installed $installed new font(s)."
} else {
Print-Success "All fonts already installed."
}
# Apply the registry file
$regFile = Join-Path $fontsDir "SF Pro Display.reg"
if (Test-Path $regFile) {
& reg import $regFile *> $null
if ($LASTEXITCODE -eq 0) {
Print-Success "Applied font registry tweaks ($($regFile | Split-Path -Leaf))."
} else {
Print-Error "Failed to apply font registry tweaks (exit $LASTEXITCODE)."
}
}
}
catch {
Print-Error "Failed to install fonts: $($_.Exception.Message)"
}
}
# --- Windows Theme ---
function Apply-WindowsTheme {
<#
.SYNOPSIS
Applies the gruvbox .deskthemepack and sets the desktop wallpaper.
.DESCRIPTION
`.deskthemepack` is a self-extracting theme bundle. Launching it with
the default handler opens Settings and applies the theme silently on
modern Windows. The wallpaper is also set explicitly via the Win32
SystemParametersInfo SPI, so the desired background is used even if
the theme doesn't bundle it.
#>
Print-Header "Applying Windows theme..."
$themeFile = Join-Path $ScriptDir ".win-themes\gruvbox-win-theme.deskthemepack"
$wallpaperFile = Join-Path $ScriptDir ".wallpapers\BFD78173-A38C-4F68-BA51-06ED0CFD1B24_1_105_c.jpeg"
# 1. Apply the .deskthemepack
if (Test-Path $themeFile) {
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would apply theme: $themeFile"
}
else {
try {
Start-Process -FilePath $themeFile -ErrorAction Stop
Print-Success "Theme applied: $themeFile"
# Theme application is async via Settings; give it a beat so
# our SystemParametersInfo call below isn't overwritten.
Start-Sleep -Seconds 3
}
catch {
Print-Error "Failed to apply theme: $($_.Exception.Message)"
}
}
}
else {
Print-Warning "Theme file not found: $themeFile. Skipping theme."
}
# 2. Set the wallpaper directly via Win32 SPI_SETDESKWALLPAPER (20).
# SPIF_UPDATEINIFILE (0x01) | SPIF_SENDCHANGE (0x02) = 3.
if (Test-Path $wallpaperFile) {
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would set wallpaper: $wallpaperFile"
}
else {
try {
if (-not ([System.Management.Automation.PSTypeName]'_DotfilesWallpaper').Type) {
Add-Type -TypeDefinition @"
using System.Runtime.InteropServices;
public class _DotfilesWallpaper {
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
}
"@
}
[_DotfilesWallpaper]::SystemParametersInfo(20, 0, $wallpaperFile, 3) | Out-Null
Print-Success "Wallpaper set: $wallpaperFile"
}
catch {
Print-Error "Failed to set wallpaper: $($_.Exception.Message)"
}
}
}
else {
Print-Warning "Wallpaper not found: $wallpaperFile. Skipping wallpaper."
}
}
# --- Windows Personalization (Registry) ---
# Registry subtrees captured for modern (Win10/11) Personalization state.
# `.deskthemepack` handles classic theme bits (wallpaper, named colors,
# cursors, sounds) but NOT accent/DWM colorization, light/dark mode,
# transparency, taskbar alignment, etc. Those live in HKCU and round-trip
# cleanly through reg export/import.
$PersonalizationKeys = @(
"HKCU\Control Panel\Colors",
"HKCU\Control Panel\Cursors",
"HKCU\Control Panel\Desktop\WindowMetrics",
"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize",
"HKCU\SOFTWARE\Microsoft\Windows\DWM",
"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Accent",
"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
)
# Registry subtrees that define per-user sign-in programs. Mirrors what Task
# Manager's Startup tab reads:
# - Run: the entries themselves (command lines Windows launches at sign-in).
# - StartupApproved\Run: enabled/disabled flag for each Run entry.
# - StartupApproved\StartupFolder: enabled/disabled flag for shortcuts in
# the Startup folder, which are mirrored separately to $StartupFolderDir.
$StartupKeys = @(
"HKCU\Software\Microsoft\Windows\CurrentVersion\Run",
"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run",
"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder"
)
function Set-ExplorerDefaultFolder {
<#
.SYNOPSIS
Configures File Explorer to open to the current user's profile folder
(e.g. C:\Users\<username>) instead of Quick Access / Home.
.DESCRIPTION
Overrides the "open new window" shell command for the Explorer CLSID
{52205fd8-5dfb-447d-801a-d0b52f2e83e1} so that clicking the taskbar
icon or pressing Win+E opens the user's home folder. Uses the
shell:profile moniker which resolves generically to %USERPROFILE%
regardless of the actual username.
#>
Print-Header "Setting File Explorer default folder to user profile..."
$clsidKey = "HKCU:\Software\Classes\CLSID\{52205fd8-5dfb-447d-801a-d0b52f2e83e1}\shell\opennewwindow\command"
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would set Explorer default folder to shell:profile via $clsidKey"
return
}
try {
if (-not (Test-Path $clsidKey)) {
New-Item -Path $clsidKey -Force -ErrorAction Stop | Out-Null
}
Set-ItemProperty -Path $clsidKey -Name "(Default)" -Value "explorer.exe shell:profile" -Force -ErrorAction Stop
Set-ItemProperty -Path $clsidKey -Name "DelegateExecute" -Value "" -Force -ErrorAction Stop
Print-Success "File Explorer will now open to the user profile folder."
}
catch {
Print-Error "Failed to set Explorer default folder: $($_.Exception.Message)"
}
}
function Configure-Desktop {
<#
.SYNOPSIS
Configures desktop settings (hides icons and auto-hides taskbar).
#>
Print-Header "Configuring Windows desktop..."
$needsExplorerRestart = $false
# 1. Hide All Desktop Icons
$advancedKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would set HideIcons = 1 in $advancedKey"
} else {
try {
if (-not (Test-Path $advancedKey)) {
New-Item -Path $advancedKey -Force -ErrorAction Stop | Out-Null
}
$currentHideIcons = Get-ItemProperty -Path $advancedKey -Name "HideIcons" -ErrorAction SilentlyContinue
if (-not $currentHideIcons -or $currentHideIcons.HideIcons -ne 1) {
New-ItemProperty -Path $advancedKey -Name "HideIcons" -PropertyType DWord -Value 1 -Force -ErrorAction Stop | Out-Null
Print-Success "Desktop icons hidden."
$needsExplorerRestart = $true
} else {
Print-Success "Desktop icons already hidden."
}
} catch {
Print-Error "Failed to hide desktop icons: $($_.Exception.Message)"
}
}
# 1b. Hide Recycle Bin specifically (NewStartPanel & ClassicStartMenu)
$hideDesktopIconsKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel"
$hideDesktopIconsKeyClassic = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu"
$recycleBinGuid = "{645FF040-5081-101B-9F08-00AA002F954E}"
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would hide Recycle Bin in $hideDesktopIconsKey"
} else {
try {
if (-not (Test-Path $hideDesktopIconsKey)) { New-Item -Path $hideDesktopIconsKey -Force -ErrorAction Stop | Out-Null }
if (-not (Test-Path $hideDesktopIconsKeyClassic)) { New-Item -Path $hideDesktopIconsKeyClassic -Force -ErrorAction Stop | Out-Null }
$currentRb = Get-ItemProperty -Path $hideDesktopIconsKey -Name $recycleBinGuid -ErrorAction SilentlyContinue
$currentRbClassic = Get-ItemProperty -Path $hideDesktopIconsKeyClassic -Name $recycleBinGuid -ErrorAction SilentlyContinue
if (-not $currentRb -or $currentRb.$recycleBinGuid -ne 1 -or -not $currentRbClassic -or $currentRbClassic.$recycleBinGuid -ne 1) {
New-ItemProperty -Path $hideDesktopIconsKey -Name $recycleBinGuid -PropertyType DWord -Value 1 -Force -ErrorAction Stop | Out-Null
New-ItemProperty -Path $hideDesktopIconsKeyClassic -Name $recycleBinGuid -PropertyType DWord -Value 1 -Force -ErrorAction Stop | Out-Null
Print-Success "Recycle Bin icon hidden."
$needsExplorerRestart = $true
} else {
Print-Success "Recycle Bin icon already hidden."
}
} catch {
Print-Error "Failed to hide Recycle Bin: $($_.Exception.Message)"
}
}
# 2. Auto-hide Taskbar
$stuckRectsKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3"
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would set taskbar to auto-hide in $stuckRectsKey"
} else {
try {
if (Test-Path $stuckRectsKey) {
$settings = (Get-ItemProperty -Path $stuckRectsKey -Name "Settings" -ErrorAction Stop).Settings
if ($settings.Length -ge 9 -and $settings[8] -ne 3) {
$settings[8] = 3
Set-ItemProperty -Path $stuckRectsKey -Name "Settings" -Value ([byte[]]$settings) -Force -ErrorAction Stop
Print-Success "Taskbar auto-hide enabled."
$needsExplorerRestart = $true
} elseif ($settings.Length -ge 9 -and $settings[8] -eq 3) {
Print-Success "Taskbar auto-hide already enabled."
} else {
Print-Warning "Taskbar settings data is invalid or missing."
}
} else {
Print-Warning "Taskbar settings key not found: $stuckRectsKey"
}
} catch {
Print-Error "Failed to enable taskbar auto-hide: $($_.Exception.Message)"
}
}
# 3. Restart Explorer to apply changes (prevents Explorer from overwriting them on exit)
if ($needsExplorerRestart -and -not $DryRun) {
Print-Header "Restarting Windows Explorer to apply desktop/taskbar changes..."
try {
Stop-Process -Name explorer -Force -ErrorAction Stop
Print-Success "Explorer restarted."
} catch {
Print-Warning "Failed to restart Explorer. Changes may require a manual sign out/in."
}
}
}
function Backup-WindowsPersonalization {
<#
.SYNOPSIS
Exports HKCU subtrees that hold modern Personalization state (accent
color, light/dark mode, transparency, cursors, classic colors,
window metrics, Explorer UI tweaks) into a single .reg file.
.DESCRIPTION
`reg export` emits UTF-16 LE with a
"Windows Registry Editor Version 5.00" header per file. We export
each key to a temp file, then concatenate by keeping the header
from the first file and stripping it from the rest so the combined
file is still a valid single .reg document for `reg import`.
#>
Print-Header "Backing up Windows personalization (registry)..."
if ($DryRun) {
foreach ($k in $PersonalizationKeys) {
Print-Warning "`[DRY RUN`] Would export: $k"
}
Print-Warning "`[DRY RUN`] Would write combined file: $PersonalizationRegFile"
return
}
$tmpFiles = @()
try {
foreach ($k in $PersonalizationKeys) {
$tmp = [System.IO.Path]::GetTempFileName()
& reg export $k $tmp /y *> $null
if ($LASTEXITCODE -eq 0 -and (Test-Path $tmp) -and (Get-Item $tmp).Length -gt 0) {
$tmpFiles += $tmp
}
else {
Print-Warning "Could not export (may not exist on this machine): $k"
if (Test-Path $tmp) { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
}
}
if ($tmpFiles.Count -eq 0) {
Print-Warning "No registry subtrees exported. Skipping."
return
}
# Keep the first file's header; drop the duplicate header from the rest.
$combined = Get-Content -Path $tmpFiles[0] -Raw -Encoding Unicode
for ($i = 1; $i -lt $tmpFiles.Count; $i++) {
$body = Get-Content -Path $tmpFiles[$i] -Raw -Encoding Unicode
$body = $body -replace '^Windows Registry Editor Version 5\.00\r?\n\r?\n', ''
$combined += $body
}
$parent = Split-Path -Parent $PersonalizationRegFile
if (-not (Test-Path $parent)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
# Unicode encoding = UTF-16 LE with BOM, which is what `reg import` expects.
Set-Content -Path $PersonalizationRegFile -Value $combined -Encoding Unicode -NoNewline
Print-Success "Personalization registry backed up to $PersonalizationRegFile."
}
finally {
foreach ($tmp in $tmpFiles) {
if (Test-Path $tmp) { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
}
}
}
function Restore-WindowsPersonalization {
<#
.SYNOPSIS
Imports the personalization .reg file so accent color, light/dark
mode, transparency, cursors, and other modern Personalization
settings match the backed-up state.
.NOTES
DWM accent and Explorer UI pick up some keys live; others (title
bar tint, Start/taskbar accent) take effect on next sign-in.
#>
Print-Header "Restoring Windows personalization (registry)..."
if (-not (Test-Path $PersonalizationRegFile)) {
Print-Warning "$PersonalizationRegFile not found. Skipping."
return
}
if ($DryRun) {
Print-Warning "`[DRY RUN`] Would run: reg import $PersonalizationRegFile"
return
}
& reg import $PersonalizationRegFile *> $null
if ($LASTEXITCODE -eq 0) {
Print-Success "Personalization registry imported."