-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeta.ps1
1725 lines (1478 loc) · 59.6 KB
/
beta.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
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
# Error handling and logging setup
$ErrorActionPreference = "Stop"
$Global:CONFIG = @{
StartTime = Get-Date
Paths = @{
Cygwin = "C:\cygwin64"
Downloads = ".\downloads"
Temp = ".\temp"
Logs = ".\logs"
Cache = ".\cache"
}
}
# Create required directories
foreach ($path in $Global:CONFIG.Paths.Values) {
if (-not (Test-Path $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
}
# Initial environment check
#Write-Host "ChromeOS Installer - Environment Check" -ForegroundColor Cyan
#Write-Host "========================================" -ForegroundColor Cyan
#Write-Host "Time: $(Get-Date)" -ForegroundColor Gray
#Write-Host "User: $env:USERNAME" -ForegroundColor Gray
#Write-Host "Directory: $PWD" -ForegroundColor Gray
#Write-Host "========================================" -ForegroundColor Cyan
# Set console encoding to UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$Host.UI.RawUI.WindowTitle = "ChromeOS Installer"
# Check if running as administrator
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host "ERROR: Script must be run as Administrator" -ForegroundColor Red
Write-Host "Please right-click and select 'Run as Administrator'" -ForegroundColor Yellow
Read-Host "Press Enter to exit"
exit 1
}
# Verify Cygwin installation
$cygwinPath = $Global:CONFIG.Paths.Cygwin
if (-not (Test-Path $cygwinPath)) {
Write-Host "ERROR: Cygwin not found at $cygwinPath" -ForegroundColor Red
Write-Host "Please install Cygwin with required packages:" -ForegroundColor Yellow
Write-Host "- pv" -ForegroundColor Yellow
Write-Host "- tar" -ForegroundColor Yellow
Write-Host "- unzip" -ForegroundColor Yellow
Write-Host "- e2fsprogs" -ForegroundColor Yellow
Write-Host "- bash" -ForegroundColor Yellow
Write-Host "- dd" -ForegroundColor Yellow
Read-Host "Press Enter to exit"
exit 1
}
# Check required Cygwin tools
$requiredTools = @("bash.exe", "dd.exe", "pv.exe", "tar.exe", "unzip.exe")
$missingTools = @()
foreach ($tool in $requiredTools) {
$toolPath = Join-Path $cygwinPath "bin\$tool"
if (-not (Test-Path $toolPath)) {
$missingTools += $tool
}
}
if ($missingTools.Count -gt 0) {
Write-Host "ERROR: Missing required Cygwin tools:" -ForegroundColor Red
$missingTools | ForEach-Object { Write-Host "- $_" -ForegroundColor Yellow }
Write-Host "`nPlease install missing packages using Cygwin setup" -ForegroundColor Yellow
Read-Host "Press Enter to exit"
exit 1
}
Write-Host "Environment check passed!" -ForegroundColor Green
Write-Host "Starting installation..." -ForegroundColor Cyan
#Write-Host ""
<#
.SYNOPSIS
ChromeOS Windows Installer Script
.DESCRIPTION
Automated ChromeOS installation script for Windows that handles:
- Processor detection and compatible build selection
- Automatic download of latest stable builds
- Disk preparation and partitioning
- ChromeOS installation with Cygwin tools
.NOTES
Author: bobanilic
Version: 2.0.0
Last Updated: 2024-12-21
Requires: PowerShell 5.1+, Administrator rights, Cygwin with required packages
.PARAMETER Debug
Enables detailed debug logging
.PARAMETER SkipDiskCheck
Skips the disk validation checks
.PARAMETER RecoveryUrl
Optional URL to a specific ChromeOS recovery image
#>
#Requires -Version 5.1
#Requires -RunAsAdministrator
# Script parameters
$Debug = $false
$SkipDiskCheck = $false
$RecoveryUrl = ""
# Script initialization
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'Continue'
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
# Version information
$Global:SCRIPT_VERSION = "2.0.0"
$Global:SCRIPT_DATE = "2024-12-21"
# Script metadata
$script:metadata = @{
StartTime = [datetime]::UtcNow
UserName = $env:USERNAME
ComputerName = $env:COMPUTERNAME
PSVersion = $PSVersionTable.PSVersion.ToString()
OS = [System.Environment]::OSVersion.VersionString
ExecutionPath = $PSScriptRoot
LogFile = $null # Will be set during initialization
}
# Global configuration
$Global:CONFIG = @{
# Paths
Paths = @{
Cygwin = "C:\cygwin64"
Logs = "$env:USERPROFILE\ChromeOS_Install_Logs"
Temp = "$env:TEMP\ChromeOS_Install"
Downloads = "$env:USERPROFILE\Downloads\ChromeOS"
Cache = "$env:USERPROFILE\.chromeos-installer"
}
# Cygwin required packages
RequiredPackages = @{
'pv' = 'pv.exe'
'tar' = 'tar.exe'
'unzip' = 'unzip.exe'
'e2fsprogs' = 'mkfs.ext4.exe'
}
# ChromeOS devices and compatibility
Devices = @{
'shyvana' = @{
Description = "8th/9th Gen Intel"
MinGeneration = 8
MaxGeneration = 9
}
'jinlon' = @{
Description = "10th Gen Intel"
MinGeneration = 10
MaxGeneration = 10
}
'voxel' = @{
Description = "11th Gen Intel and above"
MinGeneration = 11
MaxGeneration = 99
}
'gumboz' = @{
Description = "AMD Ryzen"
ProcessorType = "AMD"
}
}
# Partition configuration
Partitions = @{
'EFI-SYSTEM' = @{
Guid = "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
MinSize = 512MB
Format = "FAT32"
Required = $true
}
'ROOT-A' = @{
Guid = "3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC"
MinSize = 8GB
Format = "ext4"
Required = $true
}
'STATE' = @{
Guid = "CA7D7CCB-63ED-4C53-861C-1742536059CC"
MinSize = 1GB
Format = "ext4"
Required = $true
}
}
# Installation requirements
MinimumDiskSize = 14GB
MinimumMemory = 4GB
}
# Initialize working directories
function Initialize-WorkingEnvironment {
try {
# Create necessary directories
foreach ($path in $Global:CONFIG.Paths.Values) {
if (-not (Test-Path $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
}
# Set up logging
$logDir = $Global:CONFIG.Paths.Logs
$logFile = Join-Path $logDir "chromeos_install_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
$script:metadata.LogFile = $logFile
# Create log file
if (-not (Test-Path $logFile)) {
New-Item -ItemType File -Path $logFile -Force | Out-Null
}
return $true
}
catch {
Write-Error "Failed to initialize working environment: $_"
return $false
}
}
# Enhanced logging function
function Write-InstallLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Message,
[Parameter(Mandatory=$false)]
[ValidateSet('Info', 'Warning', 'Error', 'Debug', 'Success')]
[string]$Level = 'Info',
[Parameter(Mandatory=$false)]
[switch]$NoConsole
)
try {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logMessage = "[$timestamp UTC] [$Level] $Message"
# Add to log file
if ($script:metadata.LogFile) {
Add-Content -Path $script:metadata.LogFile -Value $logMessage -Encoding UTF8
}
# Console output unless suppressed
if (-not $NoConsole) {
switch ($Level) {
'Debug' {
if ($Debug) {
Write-Host $logMessage -ForegroundColor Gray
}
}
'Warning' { Write-Warning $Message }
'Error' { Write-Host $logMessage -ForegroundColor Red }
'Success' { Write-Host $logMessage -ForegroundColor Green }
default { Write-Host $logMessage }
}
}
}
catch {
Write-Error "Logging failed: $_"
}
}
# Script banner display
function Show-Banner {
Write-Host ""
Write-Host "Current Date and Time (UTC): $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Gray
Write-Host "Current User's Login: $env:USERNAME" -ForegroundColor Gray # Using environment variable instead of metadata
Write-Host ""
$banner = @"
+====================================================+
| ChromeOS Installation Menu |
+====================================================+
| 1. Automatic Installation (Recommended) |
| 2. Custom Installation |
| 3. Verify System Requirements |
| 4. Show Available Disks |
| 5. Exit |
+====================================================+
"@
Write-Host $banner -ForegroundColor Cyan
}
# System requirements validation
function Test-Prerequisites {
try {
Write-InstallLog "Checking prerequisites..." -Level 'Info'
# Check system requirements
$requirements = Test-SystemRequirements
if (-not $requirements.IsValid) {
return $false
}
# Check processor compatibility
$processor = Get-SystemProcessor
if (-not $processor -or -not $processor.IsValid -or -not $processor.Supported) {
Write-Host "`nUnsupported processor: $($processor.Name)" -ForegroundColor Red
return $false
}
# Check available disks
$diskInfo = Get-AvailableDisks
if (-not $diskInfo -or -not $diskInfo.IsValid -or $diskInfo.Disks.Count -eq 0) {
Write-Host "`nNo suitable disks found for installation." -ForegroundColor Red
return $false
}
return $true
}
catch {
Write-InstallLog "Prerequisites check failed: $_" -Level 'Error'
return $false
}
}
function Test-SystemRequirements {
Write-InstallLog "Checking system requirements..." -Level 'Info'
try {
# Get system information
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$ram = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)
$freeSpace = [math]::Round((Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'").FreeSpace / 1GB, 2)
$arch = (Get-CimInstance Win32_OperatingSystem).OSArchitecture
# Create result object
$result = @{
IsValid = $true
Requirements = @{
AdminRights = @{
Pass = $isAdmin
Required = "Administrator"
Current = if ($isAdmin) { "Administrator" } else { "User" }
}
RAM = @{
Pass = $ram -ge 4
Required = "4GB"
Current = "$ram GB"
}
DiskSpace = @{
Pass = $freeSpace -ge 16
Required = "16GB"
Current = "$freeSpace GB"
}
Architecture = @{
Pass = $arch -eq "64-bit"
Required = "64-bit"
Current = $arch
}
}
}
# Set overall validity
$result.IsValid = $result.Requirements.AdminRights.Pass -and
$result.Requirements.RAM.Pass -and
$result.Requirements.DiskSpace.Pass -and
$result.Requirements.Architecture.Pass
Write-InstallLog "System requirements check completed. IsValid: $($result.IsValid)" -Level 'Info'
return $result
}
catch {
Write-InstallLog "Error checking system requirements: $_" -Level 'Error'
return @{
IsValid = $false
Requirements = @{}
}
}
}
# Error handling wrapper
function Invoke-WithErrorHandling {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[scriptblock]$ScriptBlock,
[Parameter(Mandatory=$true)]
[string]$ErrorMessage,
[Parameter(Mandatory=$false)]
[scriptblock]$Finally = $null
)
try {
Write-InstallLog "Starting: $ErrorMessage" -Level 'Debug'
$result = & $ScriptBlock
Write-InstallLog "Completed: $ErrorMessage" -Level 'Debug'
return $result
}
catch {
Write-InstallLog "$ErrorMessage - Failed: $_" -Level 'Error'
throw
}
finally {
if ($null -ne $Finally) {
& $Finally
}
}
}
# Cleanup function
function Remove-InstallationArtifacts {
param(
[switch]$KeepLogs
)
Write-InstallLog "Cleaning up installation artifacts..." -Level 'Debug'
$pathsToClean = @(
$Global:CONFIG.Paths.Temp,
$Global:CONFIG.Paths.Downloads
)
foreach ($path in $pathsToClean) {
if (Test-Path $path) {
Write-InstallLog "Removing directory: $path" -Level 'Debug'
Remove-Item -Path $path -Recurse -Force -ErrorAction SilentlyContinue
}
}
if (-not $KeepLogs) {
$oldLogs = Get-ChildItem -Path $Global:CONFIG.Paths.Logs -Filter "chromeos_install_*.log" |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) }
foreach ($log in $oldLogs) {
Remove-Item -Path $log.FullName -Force -ErrorAction SilentlyContinue
}
}
}
# Processor detection and compatibility check
function Get-SystemProcessor {
try {
Write-InstallLog "Detecting system processor..." -Level 'Info'
# Create result object with IsValid property
$result = New-Object PSObject -Property @{
IsValid = $false
Name = ""
Manufacturer = ""
Device = ""
Supported = $false
}
# Get processor information
$processorInfo = Get-CimInstance Win32_Processor | Select-Object -First 1
if (-not $processorInfo) {
throw "Failed to get processor information"
}
$result.Name = $processorInfo.Name
$result.Manufacturer = $processorInfo.Manufacturer
# Determine device based on processor
if ($processorInfo.Manufacturer -like "*AMD*") {
Write-InstallLog "AMD processor detected - using gumboz device" -Level 'Info'
$result.Device = "gumboz"
$result.Supported = $true
}
elseif ($processorInfo.Manufacturer -like "*Intel*") {
Write-InstallLog "Intel processor detected - using rammus device" -Level 'Info'
$result.Device = "rammus"
$result.Supported = $true
}
else {
Write-InstallLog "Unsupported processor manufacturer: $($processorInfo.Manufacturer)" -Level 'Warning'
$result.Device = "unknown"
$result.Supported = $false
}
$result.IsValid = $true
return $result
}
catch {
Write-InstallLog "Error detecting processor: $_" -Level 'Error'
return $result # Returns object with IsValid = false
}
}
# ChromeOS build fetching and selection
function Get-ChromeOSBuilds {
param (
[string]$Device
)
try {
# Create result object with IsValid property
$result = New-Object PSObject -Property @{
IsValid = $false
Builds = @()
}
# Validate device parameter
if ([string]::IsNullOrEmpty($Device)) {
throw "Device parameter is required"
}
# Mock data for demonstration
$result.Builds = @(
@{
Version = "R118-15604.0.0"
Channel = "Stable"
DownloadUrl = "https://example.com/chromeos/R118-15604.0.0"
Device = $Device
},
@{
Version = "R117-15437.0.0"
Channel = "Beta"
DownloadUrl = "https://example.com/chromeos/R117-15437.0.0"
Device = $Device
}
)
$result.IsValid = $true
return $result
}
catch {
Write-InstallLog "Error getting ChromeOS builds: $_" -Level 'Error'
return $result # Returns object with IsValid = false
}
}
function Select-ChromeOSBuild {
param (
[switch]$Interactive,
[switch]$ForceLatest
)
try {
# Create result object with IsValid property
$result = New-Object PSObject -Property @{
IsValid = $false
DownloadUrl = ""
BuildInfo = $null
}
# Get processor info
$processor = Get-SystemProcessor
if (-not $processor.Supported) {
throw "Unsupported processor detected"
}
# Get available builds
$buildsResult = Get-ChromeOSBuilds -Device $processor.Device
if (-not $buildsResult.IsValid -or $buildsResult.Builds.Count -eq 0) {
throw "No builds found for device: $($processor.Device)"
}
$builds = $buildsResult.Builds
if ($ForceLatest) {
# Get latest build
$selectedBuild = $builds | Select-Object -First 1
Write-Host "Selected latest build: $($selectedBuild.Version)" -ForegroundColor Cyan
}
elseif ($Interactive) {
# Show available builds
Write-Host "`nAvailable ChromeOS builds for $($processor.Device):" -ForegroundColor Yellow
for ($i = 0; $i -lt [Math]::Min($builds.Count, 5); $i++) {
Write-Host "$($i + 1). Version: $($builds[$i].Version) - $($builds[$i].Channel)" -ForegroundColor Cyan
}
# Let user select a build
do {
$selection = Read-Host "`nSelect a build (1-$([Math]::Min($builds.Count, 5)))"
if ($selection -match '^\d+$' -and [int]$selection -ge 1 -and [int]$selection -le [Math]::Min($builds.Count, 5)) {
$selectedBuild = $builds[$selection - 1]
break
}
Write-Host "Invalid selection. Please try again." -ForegroundColor Red
} while ($true)
}
else {
$selectedBuild = $builds | Select-Object -First 1
}
if ($selectedBuild) {
$result.IsValid = $true
$result.DownloadUrl = $selectedBuild.DownloadUrl
$result.BuildInfo = $selectedBuild
}
return $result
}
catch {
Write-InstallLog "Error selecting ChromeOS build: $_" -Level 'Error'
return $result # Returns object with IsValid = false
}
}
# ChromeOS image download and verification functions
function Get-ChromeOSImage {
param (
[Parameter(Mandatory=$true)]
[string]$Url,
[Parameter(Mandatory=$false)]
[string]$DestinationPath = $Global:CONFIG.Paths.Downloads,
[Parameter(Mandatory=$false)]
[switch]$Force
)
try {
Write-InstallLog "Preparing to download ChromeOS image..." -Level 'Info'
# Ensure destination directory exists
if (-not (Test-Path $DestinationPath)) {
New-Item -ItemType Directory -Path $DestinationPath -Force | Out-Null
}
# Generate file path
$fileName = [System.IO.Path]::GetFileName($Url)
$filePath = Join-Path $DestinationPath $fileName
# Check if file already exists
if (Test-Path $filePath) {
if ($Force) {
Write-InstallLog "Removing existing file (Force mode)" -Level 'Debug'
Remove-Item $filePath -Force
}
else {
Write-InstallLog "Found existing download: $filePath" -Level 'Debug'
$response = Read-Host "File already exists. Download again? (Y/N)"
if ($response -eq 'Y') {
Remove-Item $filePath -Force
}
else {
Write-InstallLog "Using existing file" -Level 'Info'
return $filePath
}
}
}
# Download file with progress
Write-InstallLog "Downloading ChromeOS image from: $Url" -Level 'Info'
$webClient = New-Object System.Net.WebClient
$downloadStartTime = Get-Date
$lastUpdateTime = $downloadStartTime
$lastBytesReceived = 0
# Configure timeout and headers
$webClient.Headers.Add("User-Agent", "ChromeOS-Installer/2.0")
$webClient.Timeout = 3600000 # 1 hour timeout
# Add download progress handler
$downloadProgress = 0
$webClient.DownloadProgressChanged = {
param($sender, $e)
$currentProgress = $e.ProgressPercentage
$currentTime = Get-Date
# Update progress every 1 second
if (($currentTime - $lastUpdateTime).TotalSeconds -ge 1) {
$bytesChange = $e.BytesReceived - $lastBytesReceived
$timeChange = ($currentTime - $lastUpdateTime).TotalSeconds
$currentSpeed = $bytesChange / $timeChange / 1MB
$downloaded = $e.BytesReceived / 1MB
$total = $e.TotalBytesToReceive / 1MB
# Calculate ETA
$remainingBytes = $e.TotalBytesToReceive - $e.BytesReceived
$eta = if ($currentSpeed -gt 0) {
[TimeSpan]::FromSeconds($remainingBytes / ($currentSpeed * 1MB))
} else {
[TimeSpan]::Zero
}
$status = @(
"Downloaded: {0:N2} MB of {1:N2} MB" -f $downloaded, $total
"Speed: {0:N2} MB/s" -f $currentSpeed
"ETA: {0:hh\:mm\:ss}" -f $eta
) -join " | "
Write-Progress -Activity "Downloading ChromeOS Image" `
-Status $status `
-PercentComplete $currentProgress
$lastUpdateTime = $currentTime
$lastBytesReceived = $e.BytesReceived
}
}
# Download completion handler
$webClient.DownloadFileCompleted = {
param($sender, $e)
Write-Progress -Activity "Downloading ChromeOS Image" -Completed
if ($e.Error) {
throw $e.Error
}
}
# Start download with timeout handling
$downloadTask = $webClient.DownloadFileTaskAsync($Url, $filePath)
if (-not ($downloadTask.Wait(3600000))) { # 1 hour timeout
throw "Download timed out after 1 hour"
}
Write-InstallLog "Download completed: $filePath" -Level 'Success'
# Verify download
if (-not (Test-ChromeOSImage -ImagePath $filePath)) {
throw "Image verification failed"
}
return $filePath
}
catch {
Write-InstallLog "Failed to download ChromeOS image: $_" -Level 'Error'
if (Test-Path $filePath) {
Write-InstallLog "Removing incomplete download" -Level 'Debug'
Remove-Item $filePath -Force -ErrorAction SilentlyContinue
}
throw
}
finally {
if ($webClient) {
$webClient.Dispose()
}
}
}
function Test-ChromeOSImage {
param (
[Parameter(Mandatory=$true)]
[string]$ImagePath
)
try {
Write-InstallLog "Verifying ChromeOS image: $ImagePath" -Level 'Info'
# Basic file checks
if (-not (Test-Path $ImagePath)) {
throw "Image file not found"
}
if (-not $ImagePath.EndsWith('.zip')) {
throw "Invalid file format. Expected .zip file"
}
$file = Get-Item $ImagePath
$fileSize = $file.Length / 1GB
# Size verification
if ($fileSize -lt 1) {
throw "File size too small. Expected at least 1GB, got: $($fileSize.ToString('N2'))GB"
}
# ZIP integrity check
Write-InstallLog "Checking ZIP file integrity..." -Level 'Debug'
Add-Type -AssemblyName System.IO.Compression.FileSystem
try {
[System.IO.Compression.ZipFile]::OpenRead($ImagePath).Dispose()
}
catch {
throw "ZIP file is corrupted: $_"
}
# Content verification
$expectedContent = @(
'*recovery*.bin'
)
$zipEntries = [System.IO.Compression.ZipFile]::OpenRead($ImagePath).Entries.Name
$hasRequiredFiles = $false
foreach ($pattern in $expectedContent) {
if ($zipEntries | Where-Object { $_ -like $pattern }) {
$hasRequiredFiles = $true
break
}
}
if (-not $hasRequiredFiles) {
throw "ZIP file does not contain required ChromeOS recovery files"
}
Write-InstallLog "Image verification passed successfully" -Level 'Success'
Write-InstallLog "File size: $($fileSize.ToString('N2')) GB" -Level 'Debug'
return $true
}
catch {
Write-InstallLog "Image verification failed: $_" -Level 'Error'
return $false
}
}
function Expand-ChromeOSImage {
param (
[Parameter(Mandatory=$true)]
[string]$ImagePath,
[Parameter(Mandatory=$false)]
[string]$ExtractPath = (Join-Path $Global:CONFIG.Paths.Temp "extracted")
)
try {
Write-InstallLog "Extracting ChromeOS image..." -Level 'Info'
# Ensure extract directory exists and is empty
if (Test-Path $ExtractPath) {
Remove-Item $ExtractPath -Recurse -Force
}
New-Item -ItemType Directory -Path $ExtractPath -Force | Out-Null
# Use Cygwin tools for extraction
$cygwinBash = Join-Path $Global:CONFIG.Paths.Cygwin "bin\bash.exe"
# Convert Windows paths to Cygwin paths
$cygwinImagePath = $ImagePath.Replace('\', '/').Replace('C:', '/cygdrive/c')
$cygwinExtractPath = $ExtractPath.Replace('\', '/').Replace('C:', '/cygdrive/c')
$extractCommands = @(
"cd `"$cygwinExtractPath`"",
"unzip -o `"$cygwinImagePath`"",
"for f in *.bin; do tar xf `"`$f`"; done"
)
$result = Start-Process -FilePath $cygwinBash `
-ArgumentList "-c", ($extractCommands -join "; ") `
-Wait -NoNewWindow -PassThru
if ($result.ExitCode -ne 0) {
throw "Image extraction failed with exit code: $($result.ExitCode)"
}
# Verify extraction
$extractedFiles = Get-ChildItem $ExtractPath -Recurse
Write-InstallLog "Extracted $($extractedFiles.Count) files" -Level 'Debug'
if (-not $extractedFiles) {
throw "No files were extracted"
}
Write-InstallLog "Image extraction completed successfully" -Level 'Success'
return $ExtractPath
}
catch {
Write-InstallLog "Failed to extract ChromeOS image: $_" -Level 'Error'
throw
}
}
# Disk management and installation functions
function Get-AvailableDisks {
try {
Write-InstallLog "Scanning for available disks..." -Level 'Info'
# Create a custom object to store disk information and validity
$diskInfo = New-Object PSObject -Property @{
IsValid = $false
Disks = @()
}
# Get all physical disks
$physicalDisks = Get-Disk | Where-Object {
$_.Size -ge 16GB -and # Minimum size requirement
-not $_.IsBoot -and # Not the boot disk
-not $_.IsSystem # Not the system disk
}
if ($physicalDisks) {
$diskInfo.Disks = $physicalDisks | Select-Object @(
'Number',
'FriendlyName',
@{Name='Size(GB)'; Expression={[math]::Round($_.Size / 1GB, 2)}},
'PartitionStyle',
'OperationalStatus'
)
$diskInfo.IsValid = $true
}
Write-InstallLog "Found $($diskInfo.Disks.Count) suitable disks" -Level 'Info'
return $diskInfo
}
catch {
Write-InstallLog "Error scanning for available disks: $_" -Level 'Error'
return New-Object PSObject -Property @{
IsValid = $false
Disks = @()
}
}
}
function Initialize-InstallationDisk {
param (
[Parameter(Mandatory=$true)]
[int]$DiskNumber,
[Parameter(Mandatory=$false)]
[switch]$Force
)
try {
Write-InstallLog "Initializing disk $DiskNumber for ChromeOS installation..." -Level 'Info'
# Get disk information
$disk = Get-Disk -Number $DiskNumber
if (-not $disk) {
throw "Disk $DiskNumber not found"
}
# Safety checks
if (-not $Force) {
if ($disk.IsBoot -or $disk.IsSystem) {
throw "Cannot use boot or system disk for installation"
}
if ($disk.Size -lt $Global:CONFIG.MinimumDiskSize) {
throw "Disk size too small. Required: $($Global:CONFIG.MinimumDiskSize / 1GB) GB, Available: $([math]::Round($disk.Size / 1GB, 2)) GB"
}
# Prompt for confirmation if disk has existing partitions
$existingPartitions = Get-Partition -DiskNumber $DiskNumber -ErrorAction SilentlyContinue
if ($existingPartitions) {
Write-Host "`nWARNING: Disk $DiskNumber contains existing partitions:" -ForegroundColor Yellow
$existingPartitions | Format-Table -AutoSize
$confirmation = Read-Host "All data will be erased. Continue? (Y/N)"
if ($confirmation -ne 'Y') {
throw "Operation cancelled by user"
}
}
}
# Clear and initialize disk
Write-InstallLog "Clearing disk..." -Level 'Debug'
Clear-Disk -Number $DiskNumber -RemoveData -RemoveOEM -Confirm:$false
Write-InstallLog "Initializing disk as GPT..." -Level 'Debug'
Initialize-Disk -Number $DiskNumber -PartitionStyle GPT
# Create ChromeOS partitions
$partitions = @(
@{
Name = "EFI-SYSTEM"
Size = 512MB
Type = $Global:CONFIG.Partitions['EFI-SYSTEM'].Guid
Format = "FAT32"
Label = "EFI-SYSTEM"
},
@{
Name = "ROOT-A"
Size = 8GB
Type = $Global:CONFIG.Partitions['ROOT-A'].Guid
Format = "RAW"
Label = "ROOT-A"
},
@{
Name = "STATE"
Size = 0 # Use remaining space
Type = $Global:CONFIG.Partitions['STATE'].Guid
Format = "RAW"
Label = "STATE"
}
)
# Create partitions
$createdPartitions = @()
foreach ($partition in $partitions) {
Write-InstallLog "Creating partition: $($partition.Name)" -Level 'Debug'
$newPartition = New-Partition -DiskNumber $DiskNumber `
-Size $partition.Size `
-GptType $partition.Type
if ($partition.Format -eq "FAT32") {
Format-Volume -Partition $newPartition `
-FileSystem FAT32 `
-NewFileSystemLabel $partition.Label `
-Confirm:$false
}
$createdPartitions += $newPartition
}
# Verify partitions
$verifiedPartitions = Get-Partition -DiskNumber $DiskNumber
if ($verifiedPartitions.Count -lt 3) {
throw "Partition creation failed. Expected 3 partitions, found $($verifiedPartitions.Count)"
}
Write-InstallLog "Disk initialization completed successfully" -Level 'Success'
return $createdPartitions
}
catch {
Write-InstallLog "Failed to initialize disk: $_" -Level 'Error'
throw
}
}