. "$PSScriptRoot/../Scripts/Security.ps1";

<#
    .SYNOPSIS
    Gets the name of the WSL distribution used for managing the configuration.
#>
function Get-WslDistributionName {
    return "ValhallaUbuntu";
}

<#
    .SYNOPSIS
    Gets the path to the directory containing the WSL distribution.
#>
function Get-WslDistributionPath {
    return "$env:ProgramData/PortValhalla/$(Get-WslDistributionName)";
}

<#
    .SYNOPSIS
    Gets the path to the virtual hard disk of the WSL distribution.
#>
function Get-WslDistributionDisk {
    return "$(Get-WslDistributionPath)/ext4.vhdx";
}

<#
    .SYNOPSIS
    Checks whether `wsl` is installed properly.
#>
function Test-Wsl {
    & { $null = wsl --status; $?; };
}

<#
    .SYNOPSIS
    Checks whether any WSL distributions are installed for the current user.
#>
function Test-WslDistributions {
    & { $null = wsl -l; $?; };
}

<#
    .SYNOPSIS
    Checks whether the managed distribution is installed.
#>
function Test-WslDistribution {
    & { $null = wsl -d (Get-WslDistributionName) -e true; $?; };
}

<#
    .SYNOPSIS
    Installs `wsl` on the system.
#>
function Install-Wsl {
    wsl --install --no-launch;
}

<#
    .SYNOPSIS
    Installs a Ubuntu distribution to a shared directory.
#>
function Install-WslDistribution {
    $dir = Get-WslDistributionPath;
    $root = Split-Path -Parent $dir;
    $registryPath = "HKCU:/Software/Microsoft/Windows/CurrentVersion/Lxss";
    $key = Get-Item $registryPath;
    wsl --shutdown;

    if ($key) {
        $key = $key | Rename-Item -NewName "$(Split-Path -Leaf $key)_" -PassThru;
    }

    if (-not (Test-Path $root)) {
        $null = New-Item -ItemType Directory $root;
    }

    Copy-Item -Recurse -Force (Get-AppxPackage "*Ubuntu*").InstallLocation $dir;
    Set-UserPermissions $dir;
    & "$dir\ubuntu.exe" install --root;
    wsl --shutdown;
    Remove-Item -Recurse -Force $registryPath;

    if ($key) {
        Move-Item $key.PSPath $registryPath;
    }
}

<#
    .SYNOPSIS
    Uninstalls the managed WSL distribution.
#>
function Uninstall-WslDistribution {
    wsl --unregister (Get-WslDistributionName);
}

<#
    .SYNOPSIS
    Registers the managed WSL distribution.
#>
function Register-WslDistribution {
    wsl --import-in-place (Get-WslDistributionName) (Get-WslDistributionDisk);
    wsl --set-default (Get-WslDistributionName);
}

<#
    .SYNOPSIS
    Unregisters the managed WSL distribution.
#>
function Unregister-WslDistribution {
    $wslDisk = Get-WslDistributionDisk;
    wsl --shutdown;
    $tempDisk = Rename-Item -Force $wslDisk "ext4_.vhdx" -PassThru;
    Uninstall-WslDistribution;
    Move-Item $tempDisk $wslDisk;
}