#Requires -RunAsAdministrator
<#
.SYNOPSIS
    Post-reboot scanner cleanup. Registered as a SYSTEM logon task by
    Register-ScannerCleanupTask; removes scanner installation paths, writes
    logs-ready.json for GuruRMM to pull, then unregisters itself.

    Run directly to trigger cleanup immediately without waiting for the task:
        .\Invoke-ScannerCleanup.ps1
#>

$Base      = 'C:\GuruScan'
$stateFile = "$Base\cleanup-state.json"
$state     = @{ scan_id = ''; log_root = '' }

if (Test-Path $stateFile) {
    try { $state = Get-Content $stateFile -Raw | ConvertFrom-Json } catch {}
}

$scannerPaths = @(
    'C:\EmsisoftCmd',
    'C:\AdwCleaner',
    'C:\ProgramData\HitmanPro',
    'C:\ProgramData\HitmanPro.Alert'
)

foreach ($p in $scannerPaths) {
    if (Test-Path $p) {
        Remove-Item -Path $p -Recurse -Force -ErrorAction SilentlyContinue
    }
}

# Remove scanner download EXEs (leave C:\GuruScan\ itself intact)
$downloadsPath = "$Base\downloads"
if (Test-Path $downloadsPath) {
    Remove-Item -Path $downloadsPath -Recurse -Force -ErrorAction SilentlyContinue
}

# Flag logs as ready for GuruRMM to pull
$zipPath = "$Base\reports\$($state.scan_id).zip"
@{
    scan_id    = $state.scan_id
    log_root   = $state.log_root
    zip_path   = $zipPath
    cleaned_at = (Get-Date).ToUniversalTime().ToString('o')
} | ConvertTo-Json | Set-Content "$Base\logs-ready.json" -Encoding UTF8

Remove-Item -Path $stateFile -Force -ErrorAction SilentlyContinue

Unregister-ScheduledTask -TaskName 'GuruRMM-ScannerCleanup' -Confirm:$false -ErrorAction SilentlyContinue
