PortValhalla/scripts/Common/Scripts/Software.ps1

112 lines
4 KiB
PowerShell

. "$PSScriptRoot/Operations.ps1";
. "$PSScriptRoot/System.ps1";
. "$PSScriptRoot/../Types/InstallerAction.ps1";
$null = New-Module {
. "$PSScriptRoot/../Types/InstallerAction.ps1";
$userArgument = "name";
function Start-SoftwareInstaller {
param(
[string] $Name,
[scriptblock] $Backup = $null,
[scriptblock] $Installer = $null,
[scriptblock] $Configurator = $null,
[scriptblock] $UserBackup = $null,
[scriptblock] $UserConfigurator = $null,
[Nullable[InstallerAction]] $Action,
[hashtable] $Arguments
)
[InstallerAction] $Action = & {
if ($null -ne $Action) {
$Action;
} else {
[InstallerAction]::Install;
}
};
if (-not $Name) {
$Name = Split-Path -Leaf (Split-Path -Parent ((Get-PSCallStack)[1].ScriptName));
}
Start-Operation {
$installHandler = {
param(
[string] $Name,
[InstallerAction] $Action,
[hashtable] $Arguments
)
[string] $DisplayName = $null;
if ($null -ne $Name) {
$DisplayName = "``$Name``";
} else {
$DisplayName = "unknown software";
}
$Arguments ??= @{ };
$argumentList = @{
name = $Name;
installer = $installHandler;
arguments = $Arguments;
};
switch ($Action) {
([InstallerAction]::Backup) {
if ($Backup) {
Write-Host "Backing up $DisplayName";
& $Backup @argumentList;
}
}
([InstallerAction]::Install) {
if ($Installer) {
Write-Host "Installing $DisplayName";
& $Installer @argumentList;
}
& $installHandler @argumentList -Action ([InstallerAction]::Configure);
if ($UserConfigurator -and (-not (Test-SetupUser))) {
& $installHandler @argumentList -Action ([InstallerAction]::ConfigureUser);
}
}
([InstallerAction]::Configure) {
if ($Configurator) {
Write-Host "Configuring $DisplayName";
& $Configurator @argumentList;
}
}
default {
if ((-not $Arguments.ContainsKey($userArgument)) -or (-not $Arguments[$userArgument])) {
$Arguments.Remove($userArgument);
$Arguments.Add($userArgument, ($IsWindows ? $env:UserName : $env:USER));
}
$user = $Arguments[$userArgument];
switch ($_) {
([InstallerAction]::BackupUser) {
if ($UserBackup) {
Write-Host "Backing up $DisplayName for user ``$user``";
& $UserBackup @argumentList;
}
}
([InstallerAction]::ConfigureUser) {
if ($UserConfigurator) {
Write-Host "Configuring $DisplayName for user ``$user``";
& $UserConfigurator @argumentList;
}
}
}
}
}
};
& $installHandler -Name $Name -Action $Action -Arguments $Arguments;
};
}
}