#!/bin/pwsh
. "$PSScriptRoot/../../Scripts/KnownFolders.ps1";
. "$PSScriptRoot/../../../Common/Scripts/Context.ps1";

$null = New-Module {
    $programs32Path = $(Get-KnownFolder "ProgramFilesX86").Path;
    $vsInstaller = "$programs32Path/Microsoft Visual Studio/Installer/vs_installer.exe";

    [System.Tuple[string, string, string][]]$versions = @(
        [System.Tuple]::Create("visualstudio2019enterprise", "VisualStudio.16.Release", "Microsoft.VisualStudio.Product.Enterprise"),
        [System.Tuple]::Create("visualstudio2019community", "VisualStudio.16.Release", "Microsoft.VisualStudio.Product.Community"),
        [System.Tuple]::Create("visualstudio2022enterprise", "VisualStudio.17.Release", "Microsoft.VisualStudio.Product.Enterprise"),
        [System.Tuple]::Create("visualstudio2022community", "VisualStudio.17.Release", "Microsoft.VisualStudio.Product.Community"));

    function Get-ConfigPath([Context] $context, [string] $packageName) {
        return Join-Path $($context.BackupRoot()) "Visual Studio" $packageName ".vsconfig";
    }

    function Backup-VisualStudio([Context] $context) {
        Write-Host "Backing up Visual Studio";

        foreach ($version in $versions) {
            if ((choco list -e $version[0])) {
                Write-Information "Backing up $($version[1]): $($version[2])";

                $configPath = Get-ConfigPath $context $version[0];
                $null = New-Item -Force -ItemType Directory "$(Split-Path -Parent $configPath)";

                Start-Process -FilePath "$vsInstaller" `
                    -Wait `
                    -ArgumentList @(
                        "export",
                        "--channelId", "$($version[1])",
                        "--productId", "$($version[2])",
                        "--config", "`"$configPath`"",
                        "--quiet");
            }
        }
    }

    function Restore-VisualStudio([Context] $context) {
        Write-Host "Restoring Visual Studio";

        foreach ($version in $versions) {
            $configFileName = Get-ConfigPath $context $version[0];

            if (Test-Path $configFileName) {
                Write-Information "Restoring $($version[1]): $($version[2])";
                $arguments = "--config `"$configFileName`"";

                choco install -y $version[0] --params "$arguments";
                $context.RemoveDesktopIcon("CocosCreator*");
                $context.RemoveDesktopIcon("Unity Hub*");
            }
        }
    }
}