Wsl.ps1

# https://cloudbytes.dev/snippets/how-to-install-multiple-instances-of-ubuntu-in-wsl2

function Connect-Wsl() {
  param(
    [Parameter(Position = 0, Mandatory = $true, HelpMessage = "Enter a virtual machine name")]
    [string] $Name,
    [switch] $New 
  )

  if ($New) {
    New-Wsl $Name
  }

  wsl --distribution $Name --cd '~' --user 'box'
}

function Get-WslPath {
  param(
    [string] $Name
  )

  $path = Get-BoxPath -Path "wsl"
  if ($Name) {
    $path = Join-Path $path $Name
  }
  return $path
}
function Get-UbuntuImage {

  $imagesPath = Get-WslPath "images"
  if (!(test-path $imagesPath)) { mkdir -Path $imagesPath | out-null }

  $file = "ubuntu-noble-wsl-amd64-wsl.rootfs.tar.gz"
  $path = Join-Path $imagesPath $file

  if (-not(Test-Path $path)) {

    Write-Host("Dowloading Ubuntu image ...")

    $url = (("https://cloud-images.ubuntu.com", "wsl/noble/20240805/", $file) -join "/")
  
    $ProgressPreference = 'SilentlyContinue'
    Invoke-WebRequest $url -OutFile $path
    $ProgressPreference = 'Continue'
  }

  return $path
}

# Exported
function Get-Wsl() {
  wsl -l -v
}

# Exported
function New-Wsl() {
  param(
    [Parameter(Mandatory = $true)]
    [string] $Name
  )

  $imagePath = Get-UbuntuImage
  $instancesPath = Get-WslPath "instances"
  if (!(Test-Path $instancesPath)) { mkdir -Path $instancesPath | out-null }

  $installationPath = Join-Path $instancesPath $Name
  if (!(Test-Path $installationPath)) { mkdir -Path $installationPath | out-null } 


  Write-Host($diskPath)
  if (-Not(Test-Path (Join-Path $installationPath "ext4.vhdx") -PathType Leaf )) {
    Write-Host("Importing $name ...")
    wsl --import $name $installationPath $imagePath
    wsl --distribution $Name -- useradd -m -G sudo -s /bin/bash "box" 
    wsl --distribution $Name -- passwd "box"
    wsl --distribution $Name -- hostnamectl set-hostname $Name
    wsl --distribution $Name -- usermod -aG docker "box"
  }
}

function Remove-Wsl() {
  param(
    [Parameter(Mandatory = $true)]
    [string] $Name
  )

  wsl --unregister $Name

}