. "$PSScriptRoot/../Scripts/Context.ps1";

function New-PersonalUser([Context] $context)
{
    if (-not (Get-LocalUser $context.UserName))
    {
        Write-Host "Creating Personal User";

        while ($true) {
            Write-Host (
                [string]::Join(
                    "`n",
                    "So... Windows is too dumb to create users which are bound to a Microsoft Account.",
                    "Thus, you have to do it by yourself.",
                    "So sorry..."));

            $users = Get-LocalUser | ForEach-Object { $_.Name };
            Write-Host "Following users exist already:"
            Write-Host $users;
            Read-Host "Please hit enter once you're done...";

            $user = Get-LocalUser | Where-Object { -not ($users -contains $_.Name) } | Select-Object -Last 1;

            if ($user) {
                Write-Information "Found New User:";
                Write-Information $user;
                break;
            }
        }

        Write-Information "Renaming the new User to $($context.UserName)";
        Rename-LocalUser $user $context.UserName;
        Add-LocalGroupMember -Group "Administrators" -Member $user && Set-LocalUser $context.AdminName -Password (ConvertTo-SecureString -AsPlainText "Admin");

        Write-Host "Registering setup script for all new users";
        $context.RegisterNewUserReboot();
        Enable-UACNextLogin;
        $context.RemoveAutologin();
        Restart-Computer;
        exit;
    }
}

function Enable-UACNextLogin() {
    $taskName = "PortValhalla"
    $keyPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System";
    $propertyName = "EnableLUA";
    Set-ItemProperty "$keyPath" -Name "$propertyName" -Value 1;

    $action = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument ("-c " + `
        "Set-ItemProperty `"$keyPath`" -Name `"$propertyName`" -Value 0;" + `
        "Unregister-ScheduledTask $taskName;");
    $trigger = New-ScheduledTaskTrigger -AtLogOn;
    $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest;
    $task = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger;
    Register-ScheduledTask $taskName $task;
}