93 lines
4.8 KiB
PowerShell
93 lines
4.8 KiB
PowerShell
#Requires -RunAsAdministrator
|
|
param(
|
|
[Parameter(Mandatory)][string]$Operator,
|
|
[string]$AppRoot = (Join-Path $env:ProgramFiles 'LanUps'),
|
|
[switch]$EnableShutdown
|
|
)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
$agent = Join-Path $appRoot 'Agent\LanUps.Agent.exe'
|
|
$desktop = Join-Path $appRoot 'Desktop\LanUps.Desktop.exe'
|
|
foreach ($app in @($agent, $desktop)) {
|
|
if (!(Test-Path -LiteralPath $app -PathType Leaf)) { throw "Missing $app" }
|
|
}
|
|
$operatorSid = ([Security.Principal.NTAccount]::new($Operator)).Translate([Security.Principal.SecurityIdentifier]).Value
|
|
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps'
|
|
$token = Join-Path $data 'agent.token'
|
|
New-Item -ItemType Directory -Path $data -Force | Out-Null
|
|
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
|
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
|
|
$operatorId = [Security.Principal.SecurityIdentifier]::new($operatorSid)
|
|
$directoryRules = [Security.AccessControl.DirectorySecurity]::new()
|
|
$directoryRules.SetAccessRuleProtection($true, $false)
|
|
foreach ($principalId in @($system, $administrators)) {
|
|
$directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
|
}
|
|
$directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'ReadAndExecute', 'Allow'))
|
|
Set-Acl -LiteralPath $data -AclObject $directoryRules
|
|
if (!(Test-Path -LiteralPath $token)) {
|
|
& $agent --provision
|
|
if ($LASTEXITCODE) { throw 'Unable to create local Agent credential' }
|
|
}
|
|
$tokenRules = [Security.AccessControl.FileSecurity]::new()
|
|
$tokenRules.SetAccessRuleProtection($true, $false)
|
|
foreach ($principalId in @($system, $administrators)) {
|
|
$tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'Allow'))
|
|
}
|
|
$tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'Read', 'Allow'))
|
|
Set-Acl -LiteralPath $token -AclObject $tokenRules
|
|
|
|
$command = '"' + $agent + '"'
|
|
if ($EnableShutdown) { $command += ' --enable-shutdown' }
|
|
$installed = Get-CimInstance Win32_Service -Filter "Name='LanUps.Agent'"
|
|
if ($installed) {
|
|
Stop-Service 'LanUps.Agent' -ErrorAction Stop
|
|
$changed = Invoke-CimMethod -InputObject $installed -MethodName Change -Arguments @{PathName=$command;StartMode='Automatic'}
|
|
if ($changed.ReturnValue) { throw "Cannot update Agent service: $($changed.ReturnValue)" }
|
|
} else {
|
|
New-Service -Name 'LanUps.Agent' -BinaryPathName $command -DisplayName 'LAN UPS Agent' -StartupType Automatic | Out-Null
|
|
}
|
|
$sc = Join-Path $env:SystemRoot 'System32\sc.exe'
|
|
& $sc failure 'LanUps.Agent' reset= 86400 actions= 'restart/5000/restart/15000/restart/60000'
|
|
if ($LASTEXITCODE) { throw 'Cannot configure Agent service recovery' }
|
|
& $sc failureflag 'LanUps.Agent' 1
|
|
if ($LASTEXITCODE) { throw 'Cannot enable Agent service recovery' }
|
|
Start-Service -Name 'LanUps.Agent'
|
|
|
|
# The SCM can report Running before Kestrel is listening.
|
|
Add-Type -AssemblyName System.Net.Http
|
|
$handler = [Net.Http.HttpClientHandler]::new()
|
|
$handler.UseProxy = $false
|
|
$client = [Net.Http.HttpClient]::new($handler)
|
|
$client.Timeout = [TimeSpan]::FromSeconds(2)
|
|
$port = 47183
|
|
$configuredPort = 0
|
|
$machinePort = [Environment]::GetEnvironmentVariable('LANUPS_AGENT_PORT', 'Machine')
|
|
if ([int]::TryParse($machinePort, [ref]$configuredPort) -and $configuredPort -in 1..65535) { $port = $configuredPort }
|
|
$address = "http://127.0.0.1:$port/status"
|
|
$client.DefaultRequestHeaders.Add('X-LanUps-Token', [IO.File]::ReadAllText($token).Trim())
|
|
$deadline = [DateTime]::UtcNow.AddSeconds(25)
|
|
$ready = $false
|
|
try {
|
|
do {
|
|
try {
|
|
$status = $client.GetStringAsync($address).GetAwaiter().GetResult() | ConvertFrom-Json
|
|
if (!$status.endpoint -or !$status.update) { throw 'Unexpected Agent status response' }
|
|
$ready = $true
|
|
} catch {
|
|
$reason = $_.Exception.GetBaseException().Message
|
|
Start-Sleep -Milliseconds 300
|
|
}
|
|
} until ($ready -or [DateTime]::UtcNow -ge $deadline)
|
|
} finally { $client.Dispose() }
|
|
if (!$ready) {
|
|
$state = (Get-Service 'LanUps.Agent').Status
|
|
throw "Agent service did not respond at $address (service state: $state). $reason"
|
|
}
|
|
|
|
$action = New-ScheduledTaskAction -Execute $desktop -Argument '--tray' -WorkingDirectory (Split-Path -Parent $desktop)
|
|
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $Operator
|
|
$principal = New-ScheduledTaskPrincipal -UserId $Operator -LogonType Interactive -RunLevel Limited
|
|
Register-ScheduledTask -TaskName 'LanUps Desktop' -Action $action -Trigger $trigger -Principal $principal -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) -Force | Out-Null
|
|
Start-ScheduledTask -TaskName 'LanUps Desktop'
|