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

function Install-PersonalUsers([Context] $context) {
    $null = New-Module {
        $userIDProperty = "User";

        function Get-UserID {
            return $context.Get($userIDProperty);
        }
        function Set-UserID {
            param([int]$value);
            $context.Set($userIDProperty, $value);
        }
    }

    $userID = Get-UserID;

    if ($null -eq $userID) {
        Set-UserID ($context.UserNames.Count - 1);
        $userID = Get-UserID;
    }

    if ($userID -ge 0) {
        New-PersonalUser $context $($context.UserNames[$userID]);
        Set-UserID ($userID - 1);
    } else {
        Get-LocalUser | Where-Object { $_.Name -in $context.UserNames } |
            Enable-LocalUser;
    }
}