# installLinuxOnWindows10.ps1
# Please don't try to run this on target OS Windoze XP or even 2008
# A Windows 10 target is required. Build 19041 or higher is compulsory to upgrade to "Windows Subsystem for Linux" (WSL) version 2

$distroUrl='https://aka.ms/wslubuntu2004'
$outFile='C:\_linux\Ubuntu.zip'
$wsl2Url='https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi'
$wsl2File='C:\Temp\wsl2.msi'
$folderName='Ubuntu'
function addLinuxToWindows{
  param(
    $wsl2Url='https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi',
    $wsl2File='C:\Temp\wsl2.msi'
  )

  function includeSubsystemLinux{
    $ErrorActionPreference='stop'
    try{
      $wsl=get-command wsl -EA SilentlyContinue
      if(!$wsl){
        dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
        write-warning "Please restart this computer $env:computername before upgrading WSL to version 2."
      }      
      return $true
    }catch{
        write-warning $error[0].exception.message
        return $false
    }
  }

  $osVersion=[System.Environment]::OSVersion.Version
  $windowsMajorVersion=$osVersion.Major
  $build=$osVersion.Build
  $subsystemLinux=includeSubsystemLinux $wsl2Url $wsl2File
  if($windowsMajorVersion -ge 10 -and $build -ge 19041 -and $subsystemLinux){
    $wsl2Ready=wsl --set-default-version 2|?{$_.trim() -eq 'For information on key differences with WSL 2 please visit https://learn.microsoft.com/en-us/windows/wsl/compare-versions'}
    if(!$wsl2Ready){
      dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
      Invoke-WebRequest -Uri $wsl2Url -OutFile $wsl2File -UseBasicParsing
      #msiexec.exe /i $wsl2File /p /qn /norestart
      Start-Process -FilePath "C:\Windows\System32\msiexec.exe" -ArgumentList '/i "$wsl2File" /p /qn /norestart' -NoNewWindow -Wait
      wsl --set-default-version 2
    }
    write-host "Windows Subsystem for Linux version 2 is available on $env:computername" -ForegroundColor Green
    return $true
  }else{
        write-warning "$env:computername does not meet the pre-requisites to install Linux"
        return $false
  }
}

function installUbuntu{
  param(
    $distroUrl='https://aka.ms/wslubuntu2004',
    $outFile='C:\_linux\Ubuntu.zip',
    $wsl2Url='https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi',
    $wsl2File='C:\Temp\wsl2.msi',
    $folderName='Ubuntu'
  )

  try{
    $wslReady=addLinuxToWindows $wsl2Url $wsl2File
    if(!$wslReady){
      write-warning "Cannot continue with Windows Subsystems for Linux."
      return $false
    }
    $parentFolder=split-path $outFile -Parent
    $linuxFolder="$parentFolder\$folderName"
    $folderExists=test-path $linuxFolder
    if(!$folderExists -and !(test-path $outFile)){      
      $null=mkdir $parentFolder -force
      Invoke-WebRequest -Uri $distroUrl -OutFile $outFile -UseBasicParsing
      Expand-Archive $outFile $linuxFolder
      $updatedPaths=$ENV:Path+";$linuxFolder"
      [Environment]::SetEnvironmentVariable("Path", $updatedPaths, [System.EnvironmentVariableTarget]::Machine)
      #$userenv = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
      #[System.Environment]::SetEnvironmentVariable("PATH", $userenv + $linuxFolder, "Machine")
      # Add-AppxPackage $outFile
      & "$linuxFolder\ubuntu2004.exe"
    }
  }catch{
    write-warning $_
  }
}

installUbuntu $distroUrl $outFile $wsl2Url $wsl2File $folderName