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

function Backup-WindowsInstallation([Context] $context) {
    Write-Information "Backing up Windows";
    $backupRoot = $context.BackupRoot();
    Backup-PersonalFiles $context;
    Backup-PersonalApps $context;
    $context.Backup($backupRoot, "$backupRoot.7z", @("-sdel"));
}

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 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());
    }

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