Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

topgrade/sync-wsl-cgroup-workaround.ps1

Raw
[CmdletBinding()]
param(
    [string] $ConfigPath = (Join-Path $HOME '.wslconfig'),
    [version] $WslVersion
)

$ErrorActionPreference = 'Stop'
$managedContent = @'
# Managed by dotfiles/topgrade/sync-wsl-cgroup-workaround.ps1 for affected WSL versions.
[wsl2]
isolateDistroCgroup=false
'@ + [Environment]::NewLine

if (-not $PSBoundParameters.ContainsKey('WslVersion')) {
    $versionOutput = wsl.exe --version
    if ($LASTEXITCODE -ne 0) {
        throw "wsl.exe --version failed with exit code $LASTEXITCODE"
    }

    $versionText = ($versionOutput -join "`n") -replace "`0", ''
    $match = [regex]::Match($versionText, '\d+\.\d+\.\d+\.\d+')
    if (-not $match.Success) {
        throw 'Cannot determine the WSL version.'
    }
    $WslVersion = [version] $match.Value
}

$affected = $WslVersion -ge [version] '2.9.8.0' -and $WslVersion -le [version] '2.9.11.0'
$currentContent = if (Test-Path -LiteralPath $ConfigPath) {
    Get-Content -LiteralPath $ConfigPath -Raw
}

if ($affected) {
    if ($null -eq $currentContent) {
        Set-Content -LiteralPath $ConfigPath -Value $managedContent -NoNewline
        Write-Host "Applied WSL cgroup workaround for WSL $WslVersion. Run 'wsl --shutdown' to activate it."
    }
    elseif ($currentContent -ne $managedContent) {
        throw "$ConfigPath exists and is not managed by this script."
    }
}
elseif ($currentContent -eq $managedContent) {
    Remove-Item -LiteralPath $ConfigPath
    Write-Host "Removed obsolete WSL cgroup workaround for WSL $WslVersion. Run 'wsl --shutdown' to activate isolation."
}