param( [string]$Directory = (Join-Path $env:LOCALAPPDATA 'AndroidDeviceStreaming/agent'), [switch]$PasswordFromStdin ) $ErrorActionPreference = 'Stop' $root = [System.IO.Path]::GetFullPath($Directory).TrimEnd('\') $expected = [System.IO.Path]::GetFullPath((Join-Path $env:LOCALAPPDATA 'AndroidDeviceStreaming/agent')).TrimEnd('\') if (-not $root.Equals($expected, [System.StringComparison]::OrdinalIgnoreCase)) { throw 'Unexpected installation directory; refusing to replace files or stop processes' } $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $taskName = 'ADS-Agent' $runner = Join-Path $root 'run-agent.ps1' $executable = Join-Path $root 'ads-agent.exe' $files = @('ads-agent.exe', 'run-agent.ps1', 'agent.json', 'agent.env') foreach ($file in $files) { if (-not (Test-Path -LiteralPath (Join-Path $root ($file + '.new')))) { throw "Missing staging file: $file.new" } } $newConfig = Get-Content -LiteralPath (Join-Path $root 'agent.json.new') -Raw | ConvertFrom-Json if (-not $newConfig.server.StartsWith('wss://') -or -not $newConfig.device -or -not $newConfig.target) { throw 'Invalid gateway configuration' } $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue if ($existingTask) { $owned = @($existingTask.Actions | Where-Object { $_.Arguments -and $_.Arguments.IndexOf($runner, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count -gt 0 if (-not $owned) { throw 'A different task already owns ADS-Agent; refusing to overwrite it' } Stop-ScheduledTask -TaskName $taskName } Get-Process ads-agent -ErrorAction SilentlyContinue | Where-Object { $_.Path -and $_.Path.Equals($executable, [System.StringComparison]::OrdinalIgnoreCase) } | Stop-Process -Force $stamp = Get-Date -Format yyyyMMdd-HHmmss foreach ($file in $files) { $destination = Join-Path $root $file if (Test-Path -LiteralPath $destination) { Copy-Item -LiteralPath $destination -Destination ($destination + '.backup-' + $stamp) } Move-Item -LiteralPath (Join-Path $root ($file + '.new')) -Destination $destination -Force } $account = $identity.Name $shell = Get-Command pwsh.exe -ErrorAction SilentlyContinue $shellPath = if ($shell) { $shell.Source } else { "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" } $action = New-ScheduledTaskAction -Execute $shellPath ` -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$runner`"" -WorkingDirectory $root $triggers = @((New-ScheduledTaskTrigger -AtStartup), (New-ScheduledTaskTrigger -AtLogOn -User $account)) $settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 999 ` -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) ` -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Hidden $principal = New-ScheduledTaskPrincipal -UserId $account -LogonType Password -RunLevel Limited $task = New-ScheduledTask -Action $action -Trigger $triggers -Settings $settings -Principal $principal if ($PasswordFromStdin) { $password = [Console]::In.ReadLine() } else { $credential = Get-Credential -UserName $account -Message 'Account password for unattended gateway startup' $password = $credential.GetNetworkCredential().Password } try { Register-ScheduledTask -TaskName $taskName -InputObject $task -User $account -Password $password -Force | Out-Null } finally { $password = $null } Start-ScheduledTask -TaskName $taskName Start-Sleep -Seconds 2 Get-ScheduledTask -TaskName $taskName | Select-Object TaskName,State Get-ScheduledTaskInfo -TaskName $taskName | Select-Object LastRunTime,LastTaskResult Write-Output "Installed gateway in $root"