From ca48cf372cfa383fc6d4245d47083f9e55563e8e Mon Sep 17 00:00:00 2001
From: Weiqi Gao <gaoweiqicarl1@163.com>
Date: Wed, 17 May 2023 21:56:39 +0800
Subject: [PATCH] Fix install scripts (#518)

* Use pwsh 7 in higher priority

* Auto switch to file directory

* Only merge resources when makepri.exe exists

* Fix the error on PowerShell store version

---------

Co-authored-by: Howard Wu <HowardWu20@outlook.com>
---
 installer/Install.ps1 | 61 +++++++++++++++++++++++++++++++------------
 installer/MakePri.ps1 |  8 +++---
 installer/Run.bat     |  2 ++
 3 files changed, 51 insertions(+), 20 deletions(-)

diff --git a/installer/Install.ps1 b/installer/Install.ps1
index 6f01e5b..340b19c 100644
--- a/installer/Install.ps1
+++ b/installer/Install.ps1
@@ -48,49 +48,69 @@ Function Test-CommandExist {
 } #end function Test-CommandExist
 
 function Finish {
-    Write-Output "Optimizing VHDX size...."
-    If (Test-CommandExist Optimize-VHD) { Optimize-VHD ".\*.vhdx" -Mode Full }
+    Clear-Host
+    If (Test-CommandExist Optimize-VHD) {
+        Write-Output "Optimizing VHDX size...."
+        Optimize-VHD ".\*.vhdx" -Mode Full
+    }
     Clear-Host
     Start-Process "wsa://com.topjohnwu.magisk"
     Start-Process "wsa://com.android.vending"
 }
 
+If (Test-CommandExist pwsh.exe) {
+    $pwsh = "pwsh.exe"
+}
+Else {
+    $pwsh = "powershell.exe"
+}
+
 If (-Not (Test-Administrator)) {
     Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force
-    $Proc = Start-Process -PassThru -WindowStyle Hidden -Verb RunAs ConHost.exe -Args "powershell -ExecutionPolicy Bypass -Command Set-Location '$PSScriptRoot'; &'$PSCommandPath' EVAL"
-    $Proc.WaitForExit()
-    If ($Proc.ExitCode -Ne 0) {
-        Clear-Host
+    $Proc = Start-Process -PassThru -Verb RunAs $pwsh -Args "-ExecutionPolicy Bypass -Command Set-Location '$PSScriptRoot'; &'$PSCommandPath' EVAL"
+    If ($null -Ne $Proc) {
+        $Proc.WaitForExit()
+    }
+    If ($null -Eq $Proc -Or $Proc.ExitCode -Ne 0) {
         Write-Warning "Failed to launch start as Administrator`r`nPress any key to exit"
         $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
     }
     exit
 }
 ElseIf (($args.Count -Eq 1) -And ($args[0] -Eq "EVAL")) {
-    Start-Process ConHost.exe -Args "powershell -ExecutionPolicy Bypass -Command Set-Location '$PSScriptRoot'; &'$PSCommandPath'"
+    Start-Process $pwsh -NoNewWindow -Args "-ExecutionPolicy Bypass -Command Set-Location '$PSScriptRoot'; &'$PSCommandPath'"
     exit
 }
 
 $FileList = Get-Content -Path .\filelist.txt
 If (((Test-Path -Path $FileList) -Eq $false).Count) {
-    Write-Error "Some files are missing in the folder. Please try to build again. Press any key to exist"
+    Write-Error "Some files are missing in the folder. Please try to build again. Press any key to exit"
     $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
     exit 1
 }
 
-If ((Test-Path -Path "MakePri.ps1") -Eq $true) {
-    $ProcMakePri = Start-Process powershell.exe -PassThru -Args "-ExecutionPolicy Bypass -File MakePri.ps1" -WorkingDirectory $PSScriptRoot
+If (((Test-Path -Path "MakePri.ps1") -And (Test-Path -Path "makepri.exe")) -Eq $true) {
+    $ProcMakePri = Start-Process $pwsh -PassThru -NoNewWindow -Args "-ExecutionPolicy Bypass -File MakePri.ps1" -WorkingDirectory $PSScriptRoot
+    $null = $ProcMakePri.Handle
     $ProcMakePri.WaitForExit()
     If ($ProcMakePri.ExitCode -Ne 0) {
-        Write-Warning "Failed to merge resources, WSA Seetings will always be in English`r`n"
+        Write-Warning "Failed to merge resources, WSA Seetings will always be in English`r`nPress any key to continue"
+        $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
     }
+    $Host.UI.RawUI.WindowTitle = "Installing MagiskOnWSA...."
 }
 
 reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
 
+# When using PowerShell which is installed with MSIX
+# Get-WindowsOptionalFeature and Enable-WindowsOptionalFeature will fail
+# See https://github.com/PowerShell/PowerShell/issues/13866
+if ($PSHOME.contains("8wekyb3d8bbwe")) {
+    Import-Module DISM -UseWindowsPowerShell
+}
+
 If ($(Get-WindowsOptionalFeature -Online -FeatureName 'VirtualMachinePlatform').State -Ne "Enabled") {
     Enable-WindowsOptionalFeature -Online -NoRestart -FeatureName 'VirtualMachinePlatform'
-    Clear-Host
     Write-Warning "Need restart to enable virtual machine platform`r`nPress y to restart or press any key to exit"
     $Key = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
     If ("y" -Eq $Key.Character) {
@@ -109,6 +129,12 @@ $Dependencies = $Xml.Package.Dependencies.PackageDependency;
 $Dependencies | ForEach-Object {
     $InstalledVersion = Get-InstalledDependencyVersion -Name $_.Name -ProcessorArchitecture $ProcessorArchitecture;
     If ( $InstalledVersion -Lt $_.MinVersion ) {
+        If ($env:WT_SESSION) {
+            $env:WT_SESSION = $null
+            Write-Output "Dependency should be installed but Windows Terminal is in use. Restarting to conhost.exe"
+            Start-Process conhost.exe -Args "powershell.exe -ExecutionPolicy Bypass -Command Set-Location '$PSScriptRoot'; &'$PSCommandPath'"
+            exit 1
+        }
         Write-Output "Dependency package $($_.Name) $ProcessorArchitecture required minimum version: $($_.MinVersion). Installing...."
         Add-AppxPackage -ForceApplicationShutdown -ForceUpdateFromAnyVersion -Path "$($_.Name)_$ProcessorArchitecture.appx"
     }
@@ -121,7 +147,6 @@ $Installed = $null
 $Installed = Get-AppxPackage -Name $Name
 
 If (($null -Ne $Installed) -And (-Not ($Installed.IsDevelopmentMode))) {
-    Clear-Host
     Write-Warning "There is already one installed WSA. Please uninstall it first.`r`nPress y to uninstall existing WSA or press any key to exit"
     $key = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
     If ("y" -Eq $key.Character) {
@@ -132,16 +157,18 @@ If (($null -Ne $Installed) -And (-Not ($Installed.IsDevelopmentMode))) {
         exit 1
     }
 }
-Clear-Host
-Write-Output "Installing MagiskOnWSA...."
-If (Test-CommandExist WsaClient) { Start-Process WsaClient -Wait -Args "/shutdown" }
+
+If (Test-CommandExist WsaClient) {
+    Write-Output "Shutting down WSA...."
+    Start-Process WsaClient -Wait -Args "/shutdown"
+}
 Stop-Process -Name "WsaClient" -ErrorAction SilentlyContinue
+Write-Output "Installing MagiskOnWSA...."
 Add-AppxPackage -ForceApplicationShutdown -ForceUpdateFromAnyVersion -Register .\AppxManifest.xml
 If ($?) {
     Finish
 }
 ElseIf ($null -Ne $Installed) {
-    Clear-Host
     Write-Error "Failed to update.`r`nPress any key to uninstall existing installation while preserving user data.`r`nTake in mind that this will remove the Android apps' icon from the start menu.`r`nIf you want to cancel, close this window now."
     $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
     Clear-Host
diff --git a/installer/MakePri.ps1 b/installer/MakePri.ps1
index 308ab74..0103a6d 100644
--- a/installer/MakePri.ps1
+++ b/installer/MakePri.ps1
@@ -20,7 +20,8 @@ $Host.UI.RawUI.WindowTitle = "Merging resources...."
 If ((Test-Path -Path "pri") -Eq $true -And (Test-Path -Path "xml") -Eq $true) {
     $AppxManifestFile = ".\AppxManifest.xml"
     Copy-Item .\resources.pri -Destination ".\pri\resources.pri" | Out-Null
-    $ProcNew = Start-Process -PassThru makepri.exe -WindowStyle Hidden -Args "new /pr .\pri /cf .\xml\priconfig.xml /of .\resources.pri /mn $AppxManifestFile /o"
+    $ProcNew = Start-Process -PassThru makepri.exe -NoNewWindow -Args "new /pr .\pri /cf .\xml\priconfig.xml /of .\resources.pri /mn $AppxManifestFile /o"
+    $null = $ProcNew.Handle
     $ProcNew.WaitForExit()
     If ($ProcNew.ExitCode -Ne 0) {
         Write-Warning "Failed to merge resources from pris`r`nTrying to dump pris to priinfo...."
@@ -39,11 +40,12 @@ If ((Test-Path -Path "pri") -Eq $true -And (Test-Path -Path "xml") -Eq $true) {
         Write-Progress -Activity "Dumping resources" -Status "Ready" -Completed
         Clear-Host
         Write-Output "Creating pri from dumps...."
-        $ProcNewFromDump = Start-Process -PassThru -WindowStyle Hidden makepri.exe -Args "new /pr .\priinfo /cf .\xml\priconfig.xml /of .\resources.pri /mn $AppxManifestFile /o"
+        $ProcNewFromDump = Start-Process -PassThru -NoNewWindow makepri.exe -Args "new /pr .\priinfo /cf .\xml\priconfig.xml /of .\resources.pri /mn $AppxManifestFile /o"
+        $null = $ProcNewFromDump.Handle
         $ProcNewFromDump.WaitForExit()
         Remove-Item 'priinfo' -Recurse
         If ($ProcNewFromDump.ExitCode -Ne 0) {
-            Write-Warning "Failed to create resources from priinfos"
+            Write-Error "Failed to create resources from priinfos"
             exit 1
         }
     }
diff --git a/installer/Run.bat b/installer/Run.bat
index 5d9539d..f04fee8 100644
--- a/installer/Run.bat
+++ b/installer/Run.bat
@@ -17,6 +17,8 @@
 ::
 
 @echo off
+%~d0
+cd "%~dp0"
 if not exist Install.ps1 (
     echo "Install.ps1" is not found.
     echo Press any key to exit