-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap.ps1
595 lines (561 loc) · 18.2 KB
/
bootstrap.ps1
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
#Requires -Version 5
#Requires -RunAsAdministrator
[CmdletBinding()]
param (
[Parameter()]
[ValidateSet("Minimal", "Basic", "Full")]
$Plevel
)
Write-Output "Level: $Plevel"
function Write-Error([string]$message) {
[System.Console]::ForegroundColor = 'red'
[System.Console]::Error.WriteLine("Error:" + $message)
[System.Console]::ResetColor()
}
function Write-Warn([string]$message) {
[Console]::ForegroundColor = 'Yellow'
[Console]::Error.WriteLine("WARN: " + $message)
[Console]::ResetColor()
}
function Write-Verbose([string]$message) {
[Console]::ForegroundColor = 'DarkGreen'
[Console]::Error.WriteLine("Verbose: " + $message)
[Console]::ResetColor()
}
function Write-Title ($msg) {
Write-Host ":: " -ForegroundColor DarkGreen -NoNewline
Write-Host $msg -ForegroundColor Yellow
}
function TimeoutPrompt {
param (
$prompt,
$seconds2Wait
)
Write-Host $prompt -NoNewline
# $secondsCounter = 0
# $subCounter = 0
$timeout = New-TimeSpan -Seconds $seconds2Wait
$stopWatch = [System.Diagnostics.Stopwatch]::StartNew()
$Host.UI.RawUI.FlushInputBuffer()
while ($stopWatch.Elapsed -lt $timeout) {
# Start-Sleep -Milliseconds 10
# $subCounter += 10
# if ($subCounter -eq 1000) {
# $secondsCounter++
# $subCounter = 0
# Write-Host "." -NoNewline
# }
Start-Sleep -Seconds 1
Write-Host "." -NoNewline
if ($host.UI.RawUI.KeyAvailable) {
$keyPressed = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyUp, IncludeKeyDown")
if ($keyPressed.KeyDown -eq $True) {
$Host.UI.RawUI.FlushInputBuffer()
Write-Host "`r`n"
return $true
}
}
}
Write-Host "`r`n"
return $false
}
function StowFile {
param (
[string]$link,
[string]$target
)
$file = Get-Item $link -ErrorAction SilentlyContinue
$target = (Get-Item $target -ErrorAction SilentlyContinue).FullName
if ($file) {
if ($file.LinkType -ne "SymbolicLink") {
Write-Error "$($file.FullName) already exists and is not a symbolic link"
return
}
elseif ($file.Target -ne $target) {
Write-Error "$($file.FullName) already exists and points to '$($file.Target)', it should point to '$target'"
return
}
else {
Write-Verbose "$($file.FullName) already linked"
return
}
}
else {
$folder = Split-Path $link
if (-not (Test-Path $folder)) {
Write-Verbose "Creating folder $folder"
New-Item -Type Directory -Path $folder
}
Write-Verbose "Creating link $link to $target"
(New-Item -Path $link -ItemType SymbolicLink -Value $target -ErrorAction Continue).Target
}
}
function DownloadFile {
param (
[string]$url,
$target,
[string]$hash = $null
)
if (Test-Path $target) {
Write-Verbose "$target already downloaded."
$IsDownload = $true
}
else {
# download
$IsDownload = $false
try {
(New-Object System.Net.WebClient).DownloadFile($url, $target)
}
catch {
Write-Error $_
exit
}
}
if ($hash) {
$targethash = Get-FileHash $target -Algorithm "SHA256"
$diff = 0
Compare-Object -ReferenceObject $hash -DifferenceObject $targethash.Hash | ForEach-Object {
if ($_.SilentlyContinue -ne "==") {
$diff += 1
}
}
if ($diff -ne 0) {
if ($IsDownload) {
Write-Error "'$target' does not match expected hash!`nExpected: $hash`nActual: $($targethash.Hash)"
return
}
else {
Write-Error "Downloaded File '$target' from url '$url' does not match expected hash!`nExpected: $hash`nActual: $($targethash.Hash)"
return
}
}
}
if (!$IsDownload) {
Write-Verbose "$target download successful !"
}
}
function SetEnvVariable {
param (
[ValidateSet("Machine ", "Process ", "User")]
[string]$target,
[string]$name,
[string]$value
)
$existing = [System.Environment]::GetEnvironmentVariable($name, $target)
if ($existing) {
Write-Verbose "Environment variable $name already set to '$existing'"
}
else {
Write-Verbose "Adding the $name environment variable to '$value'"
[System.Environment]::SetEnvironmentVariable($name,$value,$target)
}
}
function EnsureDir ($dir) {
if (!(Test-Path $dir)) {
# Write-Output "Create folder: $dir"
mkdir $dir | Out-Null
}
Resolve-Path $dir
}
# scoop
function AddScoopLog {
param (
$message,
[bool]$isAppend = $false,
[string]$file = "$($env:HOMEDRIVE)$($env:HOMEPATH)\scoop.log"
)
if ($isAppend) {
$message >> $file
}
else {
"`n" >> $file
Get-Date -Format 'yyyy/M/d hh:mm:s' >> $file
$message >> $file
}
}
function CheckScoopBucket {
param (
[string]$bucket,
[string]$bucket_url,
[int]$count
)
begin {
if (-not [string]::IsNullOrWhiteSpace($bucket_url)) {
Write-Output "==> $bucket_url"
}
$ins_suc = $true
$log = @()
}
process {
if ($_ -cmatch 'failed|Error|bucket not found|like a valid git|missing|fatal: |try again') {
$log += "ERROR: $_"
$ins_suc = $false
Write-Error $_
}
else {
$log += $_
# Write-Output "...$_"
}
}
end {
if ($ins_suc) {
# Write-Host "成功:" -ForegroundColor Cyan -NoNewline
# Write-Host "数据库 $bucket 克隆成功" -BackgroundColor DarkGreen
Write-Verbose "Bucket $bucket added successfully!"
}
else {
# Write-Host "失败:" -ForegroundColor Red -NoNewline
# Write-Host "数据库 $bucket 克隆失败"
Write-Error "Bucket $bucket add failure."
Write-Verbose "Preparing to readd the bucket: $bucket [ $count ]"
Write-Verbose "==> scoop bucket rm $bucket"
scoop bucket rm $bucket
AddScoopBucket -bu_name $bucket -bu_url $bucket_url -count $count
AddScoopLog -message "Failed bucket:$bucket [ $count ]"
AddScoopLog -message $log -isAppend $true
}
}
}
function CheckScoopInstall {
param (
[string]$appName,
[int]$count,
[bool]$isCore = $false
)
begin {
Write-Output "`nInstall $appName"
$ins_suc = $true
$log = @()
}
process {
if ($_ -cmatch 'aborted|failed|Error|doesn''t exist|Couldn''t find') {
$log += "ERROR: $_"
$ins_suc = $false
Write-Error $_
}
else {
$log += $_
# Write-Host "...."$_
Write-Output "...$_"
}
}
end {
if ($ins_suc) {
# Write-Host "成功:" -ForegroundColor Green -NoNewline
# Write-Host "$appName 安装成功" -BackgroundColor DarkGreen
Write-Verbose "App $appName installed successful!"
}
else {
# Write-Host "失败:" -ForegroundColor Red -NoNewline
# Write-Host "$appName 安装失败"
Write-Error "App $appName install failure."
if (-not $isCore) {
if ($count -le 3) {
Write-Verbose "Preparing for reinstallation $appName [ $count ]"
Write-Output "==> scoop uninstall $appName"
scoop uninstall $appName
InsScoop -appsName $appName -count $count
}
else {
# Write-Host "失败:" -ForegroundColor Red -NoNewline
# Write-Host "安装 $appName 失败超过三次,不再尝试" -ForegroundColor DarkRed -BackgroundColor Yellow
Write-Error "App $appName install failure.(Fail more than three times)"
AddScoopLog -message "Failed Installation: $appName"
AddScoopLog -message $log -isAppend $true
}
}
else {
Write-Verbose "App $appName is core app and it being reinstalled [ $count ]"
scoop uninstall $appName
Write-Output "==> scoop uninstall $appName"
InsScoop -appsName $appName -count $count -isCore $true
}
}
}
}
function AddScoopBucket {
param (
[string]$bu_name,
[string]$bu_url,
[int]$count = 0
)
$count ++
if ([string]::IsNullOrWhiteSpace($bu_url)) {
(cmd /c "scoop bucket add $bu_name") | CheckScoopBucket -bucket $bu_name -count $count
}
else {
(cmd /c "scoop bucket add $bu_name `'$bu_url`'") | CheckScoopBucket -bucket $bu_name -count $count -bucket_url $bu_url
}
}
function InsScoop {
param (
[string]$appsName,
[int]$count = 0,
[bool]$isCore = $false
)
$count ++
(powershell.exe scoop install $appsName) | CheckScoopInstall -appName $appsName -count $count -isCore $isCore
}
# 参数转数值判断大小
$LevelMinimal = 1
$LevelBasic = 10
$levelFull = 100
$level = 0
switch ($Plevel) {
"Minimal" { $level = $LevelMinimal }
"Basic" { $level = $LevelBasic }
"Full" { $level = $levelFull }
}
#region environment configuration
# - fw
# - $env:home
# 某些设备没有这个环境变量
if (-not $env:HOME) {
$env:HOME = "$($env:HOMEDRIVE)$($env:HOMEPATH)"
}
#endregion
#region create dir and download dotfiles from github
# - create & tmp
# - unzip master.zip to tmp
# - copy powershell folder to dotfiles
# - remove tmp
Write-Title "Download Paxos` dotfiles"
Write-Output "Creating dotfiles folder..."
$dir = EnsureDir "$env:home\dotfiles"
# download dotfiles zip
$zip_url = "https://github.com/Paxxs/dotfiles-win/archive/master.zip"
$zip_file = "$dir\dotfiles.zip"
Write-Output "Downloading dotfiles in $zip_file"
DownloadFile -url $zip_url -target $zip_file
# Extract zip
Write-Output 'Extracting...'
Add-Type -AssemblyName "System.IO.Compression.FileSystem"
[IO.Compression.ZipFile]::ExtractToDirectory($zip_file, "$dir\_tmp")
Copy-Item "$dir\_tmp\*master\powershell" $dir -Recurse -Force
Remove-Item "$dir\_tmp", $zip_file -Recurse -Force
#endregion
#region powershell & install scoop
# - powershell profile
# - powershell module
# - install scoop and update first
if ($level -ge $LevelMinimal) {
Write-Title "Stow powershell legacy profile"
StowFile $Global:profile "$dir\powershell\Microsoft.PowerShell_profile.ps1"
}
if ($level -ge $LevelBasic) {
# Basic 级别安装 scoop,如果没有安装则安装
if (!(Get-Command scoop)) {
Write-Title "Install scoop"
$customScoop = TimeoutPrompt "Press key to intervene in scoop installer" 5
if ($customScoop) {
$scoopDir = Read-Host "Where do u want to install (Enter: default)"
if ($scoopDir) {
[System.Environment]::setEnvironmentVariable('SCOOP', $scoopDir, 'User')
$env:SCOOP = $scoopDir # with this we don't need to close and reopen the console
}
$scoopGlobalDir = Read-Host "Set global installation to custom directory (Enter: default)"
if ($scoopGlobalDir) {
[System.Environment]::setEnvironmentVariable('SCOOP_GLOBAL', $scoopGlobalDir, 'Machine')
$env:SCOOP_GLOBAL = $scoopGlobalDir
}
}
Invoke-Expression (new-object net.webclient).downloadstring('https://get.scoop.sh')
}
Write-Output "configure scoop alias..."
scoop alias add S 'scoop install $args[0]' 'Install apps'
scoop alias add Su 'sudo scoop install $args[0]' 'Install apps (with sudo)'
scoop alias add Ss 'scoop search $args[0]' 'Search available apps'
scoop alias add Si 'scoop info $args[0]' 'Display information about an app'
scoop alias add Sy 'scoop update $args[0]' 'Update apps, or Scoop itself'
scoop alias add Syu 'sudo scoop update *' 'Updates all apps (with sudo)'
scoop alias add R 'scoop uninstall $args[0]' 'Uninstall an app'
scoop alias add Ru 'sudo scoop uninstall $args[0]' 'Uninstall an app (with sudo)'
scoop alias add Fs 'scoop prefix $args[0]' 'Returns the path to the specified app'
Write-Title "Install basic app..."
@(
"git",
"7zip",
"sudo",
"win32-openssh"
# "fzf",
) | ForEach-Object {
# InsScoop -appsName $_
InsScoop -appsName $_ -isCore $true
}
@(
"busybox",
"curl",
"adb",
"shasum",
"gpg",
"neovim",
"connect",
"aria2"
) | ForEach-Object {
InsScoop -appsName $_ -isCore $false
}
# To get Git to recognise OpenSSH
[environment]::setenvironmentvariable('GIT_SSH', (resolve-path (scoop which ssh)), 'USER')
Write-Title "Clone scoop Bucket"
if ($level -ge $LevelMinimal) {
@(
("Extras bucket for Scoop", "extras"),
("nonportable applications", "nonportable"),
("Cluttered bucket", "MorFans", "https://github.com/Paxxs/Cluttered-bucket.git"),
("Installing nerd fonts", "nerd-fonts"),
("versions", "versions")
) | ForEach-Object {
Write-Output "Cloning bucket: "$_[0]
if ([string]::IsNullOrWhiteSpace($_[2])) {
# official
AddScoopBucket -bu_name $_[1]
}
else {
AddScoopBucket -bu_name $_[1] -bu_url $_[2]
}
}
}
if ($level -ge $LevelBasic) {
@(
("JAVA Bucket", "java"),
# ("PHP Bucket", "php"),
("h404bi`s bucket", "dorado", "https://github.com/h404bi/dorado.git"),
("Ash258 Personal bucket", "Ash258", "https://github.com/Ash258/scoop-Ash258.git"),
("Reverse engineering tools", "retools", "https://github.com/TheCjw/scoop-retools.git"),
("All Sysinternals tools separately", "Sysinternals", "https://github.com/Ash258/Scoop-Sysinternals.git")
) | ForEach-Object {
Write-Output "Cloning bucket: $($_[0])"
if ([string]::IsNullOrWhiteSpace($_[2])) {
# official
AddScoopBucket -bu_name $_[1]
}
else {
AddScoopBucket -bu_name $_[1] -bu_url $_[2]
}
}
if ($level -ge $levelFull) {
Write-Output "Cloning bucket: portableapps.com"
AddScoopBucket -bu_name "portableapps" -bu_url "https://github.com/nickbudi/scoop-bucket.git"
}
}
}
Write-Title "Install PowerShell Module"
# PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
if ($level -ge $LevelMinimal) {
Write-Verbose "Install Module: posh-git"
Install-Module posh-git -Scope CurrentUser -Force
Write-Verbose "Install Module: oh-my-posh"
Install-Module oh-my-posh -Scope CurrentUser -Force
# Administrator rights are required
Write-Verbose "Install Module: Get-ChildItemColor"
Install-Module -AllowClobber Get-ChildItemColor CurrentUser -Force
}
if ($level -ge $LevelBasic) {
if(!(Get-Command z -ErrorAction SilentlyContinue)) {
Write-Verbose "Install Module: z"
Install-Module z -AllowClobber -Scope CurrentUser -Force
}
# need the latest version of fzf.exe
# if(!(Get-Module PSFzf)) {
# Write-Verbose "Install Module: PSFzf"
# Install-Module -Name PSFzf -Force
# }
}
#endregion
#region Install Software
if ($level -ge $LevelBasic) {
Write-Title "Install application..."
@(
"extras/dismplusplus",
"extras/everything",
"MorFans/FastCopy-M",
"main/frp",
"extras/locale-emulator",
"extras/processhacker",
"extras/resource-hacker",
"MorFans/UAC.HashTab",
"extras/aria-ng-gui",
"extras/autohotkey",
"extras/filezilla",
"fzf",
"MorFans/LightProxy",
"MorFans/Malware-Patch",
"MorFans/mclone",
"nvm",
"MorFans/ProjectEye",
"python",
"dorado/qtscrcpy",
"Ash258/potplayer",
"dorado/trafficmonitor",
"MorFans/UAC.PowerToys",
"MorFans/Windows.Auto.Night.Mode",
"dorado/clash-for-windows-portable",
"MorFans/UAC.Listary5.Third"
"nerd-fonts/Cascadia-Code",
"nerd-fonts/CascadiaCode-NF",
"Noto-NF",
"SarasaGothic-ttc",
"FiraCode-NF",
"FiraMono-NF"
) | ForEach-Object {
InsScoop -appsName $_
}
}
if ($level -ge $levelFull) {
# Cspell:disable
@(
"extras/dnspy",
"extras/gifcam",
"extras/joplin",
"extras/keeweb",
# "extras/mkcert",
# "main/nodejs",
# "ojdkbuild8-full",
"extras/postman",
"extras/putty",
# "tcping",
"v2ray"
"extras/v2rayN",
"extras/authy",
# "winPython"
# "MorFans/AliWangWang",
# "MorFans/bingdian",
"dorado/chfs",
"ffmpeg",
"MorFans/FFRenamePro",
"fiddler",
# "extras/format-factory",
# "extras/googlechrome-dev",
# "dorado/hmcl",
# "MorFans/IDA-Pro.64",
# "MorFans/JJDown",
# "MorFans/LDPlayer.clear",
# "dorado/magicavoxel",
# "MorFans/mofang-PCMaster-full",
"nmap",
# "extras/obs-studio",
"extras/rufus",
# "nerd-fonts/SarasaGothic-ttc",
"extras/screentogif",
"syncthing",
# "MorFans/tb-Toolbox",
"extras/tor-browser",
# "dorado/trafficmonitor",
# "extras/typora",
# "MorFans/UAC.QQ_Portable",
# "MorFans/UAC.ThunderX",
# "MorFans/UAC.Xmind-8",
# "MorFans/UAC.xshell6",
# "MorFans/UAC.YoudaoDict.Pure",
# "MorFans/WeChat-Portable",
# "MorFans/Windows.Auto.Night.Mode",
"extras/wireshark",
"go",
"extras/bitwarden"
) | ForEach-Object {
InsScoop -appsName $_
}
# Cspell:enable
}
#endregion