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

$null = New-Module {
    $path = "$HOME/Documents/TrackMania";
    $softwareName = "TmUnitedForever";

    function Backup-TmUnited([Context] $context) {
        Write-Host "Backing up TrackMania United Forever";
        $context.Backup($path, $context.SoftwareArchive($softwareName), @("-i@`"$PSScriptRoot/include.txt`""));
    }

    function Restore-TmUnited([Context] $context) {
        $setupFile = "TmUnitedForever.exe";
        $features = @("DirectPlay", "NetFx3");
        Write-Host "Restoring TrackMania United Forever";

        foreach ($feature in $features) {
            if ((Get-WindowsOptionalFeature -Online -FeatureName $feature).State -ne "Enabled") {
                Write-Information "Enabling the ``$feature`` feature";
                Enable-WindowsOptionalFeature -Online -All -FeatureName $feature;
            }
        }

        $tempDir = $context.GetTempDirectory();
        Push-Location $tempDir;
        Write-Information "Downloading TrackMania United Forever setup";
        Invoke-WebRequest "http://files.trackmaniaforever.com/tmunitedforever_setup.exe" -OutFile "$setupFile";

        Write-Information "Installing TrackMania United Forever";
        Start-Process -Wait -FilePath $setupFile -ArgumentList @("/Silent");
        Write-Information "Removing desktop icon";
        $context.RemoveDesktopIcon("*TmUnitedForever*");
        Write-Information "Restoring files";
        $context.Restore($context.SoftwareArchive($softwareName), $path);
        Pop-Location;

        Remove-Item -Recurse $tempDir;
    }
}