#!/bin/pwsh
. "$PSScriptRoot/Manage.ps1";
. "$PSScriptRoot/Upgrade.ps1";
. "$PSScriptRoot/User.ps1";
. "$PSScriptRoot/../Scripts/Context.ps1";
. "$PSScriptRoot/../Scripts/Entrypoints.ps1";
. "$PSScriptRoot/../Software/Firefox/Install.ps1";

function Invoke-WindowsInstallation([Context] $context)
{
    $context.EntryPoint = Get-Entrypoint;
    $configPath = "$PSScriptRoot/../Config";
    $softwarePath = "$PSScriptRoot/../Software";

    if (-not $context.Get("InitialConfiguration")) {
        if ((Get-Command Initialize-Configuration -ErrorAction SilentlyContinue)) {
            Initialize-Configuration $context;
        }

        $null = Enable-WindowsOptionalFeature -Online -All -FeatureName "NetFx3";

        . "$configPath/Windows/Install.ps1" $context;
        . "$configPath/Explorer/Install.ps1" $context;
        . "$configPath/OpenSSH/Install.ps1" $context;
        . "$configPath/chocolatey/Install.ps1";

        $context.RemoveDesktopIcon("*Microsoft Edge*");
        $context.Set("InitialConfiguration", 1, "DWord");
    }

    Write-Host "Starting Installation and Restoration of Windows";
    Update-WindowsInstallation $context;

    if (-not $context.Get("SoftwarePrerequisitesInstalled")) {
        Write-Host "Installing prerequisites for installing software";

        if (-not $(Get-Command winget)) {
            choco install -y winget;
        }

        Install-Module -AcceptLicense -Force "NuGet";
        Import-Module NuGet;

        Install-Firefox $context;
        choco install -y selenium-gecko-driver;
        $null = Install-Package -Force Selenium.WebDriver -RequiredVersion 4.10.0 -SkipDependencies;

        winget install --accept-source-agreements --accept-package-agreements -e --id AutoHotkey.AutoHotkey;

        $context.Set("SoftwarePrerequisitesInstalled", 1, "DWord");
    }

    if (-not $context.Get("DriversInstalled")) {
        Write-Host "Installing Drivers";
        Write-Information "Looking for driver installation function";

        if ((Get-Command Install-PortValhallaDrivers -ErrorAction SilentlyContinue)) {
            Write-Information "Driver installation function was found. Starting installation";
            Install-PortValhallaDrivers $context;
        }

        Write-Information "Finished installing drivers";
        $context.Set("DriversInstalled", 1, "DWord");
        $context.Reboot();
        exit;
    }

    if (-not $context.Get("MachineWideSoftware")) {
        Write-Host "Setting up software with default app associations";
        . "$softwarePath/aliae/Install.ps1" $context;
        . "$softwarePath/WinSCP/Install.ps1" $context;
        . "$softwarePath/Thunderbird/Install.ps1" $context;
        . "$softwarePath/posh-git/Install.ps1";
        . "$softwarePath/Terminal-Icons/Install.ps1";
        . "$softwarePath/Oh My Posh/Install.ps1" $context;
        $context.Set("MachineWideSoftware", 1, "DWord");
    }

    New-PersonalUser $context;
    Restore-WindowsInstallation $context;
}