#!/bin/pwsh
. "$PSScriptRoot/../Scripts/PersonalFiles.ps1";
. "$PSScriptRoot/../Software/Firefox/Install.ps1";
. "$PSScriptRoot/../Software/Nextcloud/Install.ps1";
. "$PSScriptRoot/../Collections/Personal.ps1";
. "$PSScriptRoot/../../Common/Scripts/Context.ps1";

function Backup-WindowsInstallation([Context] $context) {
    Write-Information "Backing up Windows";
    $Global:InformationPreference = "Continue";
    $Global:ErrorActionPreference = "Inquire";
    . "$PSScriptRoot/../../../scripts/Windows/Scripts/Prerequisites.ps1";
    $backupRoot = $context.BackupRoot();
    Backup-PersonalFiles $context;
    Backup-PersonalApps $context;
    $context.Backup($backupRoot, "$backupRoot.7z", @("-sdel"), $false);
    $context.Cleanup();
    Write-Host "Never forget to store the backup somewhere safe!";
    Write-Host "I mean... what kind of a dumbass would ever forget to do so, right?";
}

function Restore-WindowsInstallation([Context] $context) {
    Write-Host "Restoring Windows";
    choco feature enable -n useEnhancedExitCodes;

    function Read-Path()
    {
        $backupPath = Read-Host -Prompt "Please enter the path to the archive to load the backup from.";

        if ($backupPath -and (-not (Test-Path -PathType Leaf $backupPath)))
        {
            Write-Host "No file could be found at the specified path.";
            return Read-Path;
        }
        else
        {
            return $backupPath;
        }
    }

    Install-Firefox $context;
    Restore-Nextcloud $context;

    Write-Information "Determining Backup Archive Path";
    $backupPath = Read-Path;
    $context.BackupName ??= "PortValhalla";
    $context.RootDir = $context.GetTempDirectory();

    if ($backupPath)
    {
        $context.Restore($backupPath, $context.BackupRoot());
    }

    Copy-UserInternationalSettingsToSystem -WelcomeScreen $True -NewUser $False;
    Restore-PersonalFiles $context;

    if ((Get-Command Restore-Apps -ErrorAction SilentlyContinue)) {
        Restore-Apps $context;
    }

    Remove-Item -Recurse $context.RootDir;
    $context.Cleanup();
}