# register-edr-watcher.ps1
# Register the "ClaudeTools - EDR Isolation Watcher" scheduled task on this Windows
# machine (the same box that runs GPS-RMM-AutoEnroll et al). The task runs
# edr-isolation-watch.sh every 10 minutes, which polls Datto EDR for hosts auto-
# isolated by an EDR response and posts each NEW one to #dev-alerts (Mike + Howard).
#
# Interim alerting until the GuruRMM EDR webhook integration (Feature 6) lands.
# Idempotent: -Force replaces any existing task with the same name.
#
# Run from an ordinary (non-admin) PowerShell:
#   powershell -ExecutionPolicy Bypass -File C:\claudetools\.claude\scripts\register-edr-watcher.ps1

$ErrorActionPreference = "Stop"
$TaskName = "ClaudeTools - EDR Isolation Watcher"

# Launch via a wscript.exe VBS wrapper (GUI-subsystem host) so bash starts hidden and
# NO console window flashes on the desktop every 10 min. Launching bash.exe directly is
# a console-subsystem app with LogonType=Interactive + Hidden=False -> visible flash.
# Mirrors the gps-rmm-progress-hidden.vbs fix. Do NOT revert to a raw bash.exe action.
$BashExe = "C:\Program Files\Git\bin\bash.exe"
if (-not (Test-Path $BashExe)) { Write-Host "[ERROR] Git bash not found at $BashExe" -ForegroundColor Red; exit 1 }

$ScriptWin = "C:\claudetools\.claude\scripts\edr-isolation-watch.sh"
if (-not (Test-Path $ScriptWin)) { Write-Host "[ERROR] Watcher not found at $ScriptWin" -ForegroundColor Red; exit 1 }

$WScript = "C:\Windows\System32\wscript.exe"
$Vbs     = "C:\claudetools\.claude\scripts\edr-isolation-watch-hidden.vbs"
if (-not (Test-Path $Vbs)) { Write-Host "[ERROR] Hidden wrapper not found at $Vbs" -ForegroundColor Red; exit 1 }

$Action = New-ScheduledTaskAction -Execute $WScript -Argument "`"$Vbs`""

# Every 10 minutes, indefinitely (10-year duration avoids the MaxValue quirk).
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date `
    -RepetitionInterval (New-TimeSpan -Minutes 10) `
    -RepetitionDuration (New-TimeSpan -Days 3650)

# Run as the current user, only when logged on (needs the interactive vault/env,
# same posture as the GrepAI watcher). No admin required.
$Principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Limited

$Settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
    -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 5) `
    -MultipleInstances IgnoreNew -Hidden

Register-ScheduledTask -TaskName $TaskName -Action $Action -Trigger $Trigger `
    -Principal $Principal -Settings $Settings `
    -Description "Polls Datto EDR every 10 min for auto-isolated hosts; posts new ones to #dev-alerts. Interim until GuruRMM EDR webhook (Feature 6)." -Force | Out-Null

Write-Host "[OK] Registered scheduled task: $TaskName (every 10 min)" -ForegroundColor Green
Get-ScheduledTask -TaskName $TaskName | Select-Object TaskName, State | Format-Table -AutoSize
