$ErrorActionPreference = "Stop"
$AppDir = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$RunScript = Join-Path $AppDir "scripts\run-agent.ps1"
$TaskWrapper = Join-Path $AppDir "run\start-agent-interactive.cmd"
$StartupDir = [Environment]::GetFolderPath("Startup")
$StartupShortcut = Join-Path $StartupDir "ControlCmdAgentInteractive.cmd"
$StdoutLog = Join-Path $AppDir "logs\agent.out.log"
$StderrLog = Join-Path $AppDir "logs\agent.err.log"

if ([System.Diagnostics.Process]::GetCurrentProcess().SessionId -eq 0) {
  throw "Run this installer from the logged-in Windows desktop user, not WinRM, SSH, or a Windows service."
}

New-Item -ItemType Directory -Force -Path (Join-Path $AppDir "run") | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $AppDir "logs") | Out-Null
@"
@echo off
cd /d "$AppDir"
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$RunScript" 1> "$StdoutLog" 2> "$StderrLog"
"@ | Set-Content -Encoding ASCII $TaskWrapper

Copy-Item $TaskWrapper $StartupShortcut -Force
Write-Host "Interactive startup command installed: $StartupShortcut"
Write-Host "Starting Agent now..."
Start-Process -FilePath $TaskWrapper -WindowStyle Hidden
