# Install GuruRMM Agent from temporary location
# This avoids the file-in-use error by running installer from Temp

Write-Host "[INFO] Setting up GuruRMM agent installation..."

$agentPath = "C:\Program Files\GuruRMM\gururmm-agent.exe"
$tempPath = "C:\Temp\gururmm-agent-installer.exe"
$serverUrl = "wss://rmm-api.azcomputerguru.com/ws"
$apiKey = "SWIFT-CLOUD-6910"

# Check source exists
if (!(Test-Path $agentPath)) {
    Write-Host "[ERROR] Agent binary not found at $agentPath"
    exit 1
}

Write-Host "[OK] Agent binary found"

# Stop any running processes
$processes = Get-Process -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($processes) {
    Write-Host "[WARNING] Stopping $($processes.Count) running agent process(es)..."
    foreach ($proc in $processes) {
        Stop-Process -Id $proc.Id -Force
    }
    Start-Sleep -Seconds 3
}

# Copy to temp location
Write-Host "[INFO] Copying agent to temporary location..."
Copy-Item -Path $agentPath -Destination $tempPath -Force
Write-Host "[OK] Copied to $tempPath"

# Run installer from temp location
Write-Host "[INFO] Running installer from temporary location..."
Write-Host "  Server URL: $serverUrl"
Write-Host "  API Key: $apiKey"

& $tempPath install --server-url $serverUrl --api-key $apiKey

if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] Installation failed with exit code: $LASTEXITCODE"
    Remove-Item -Path $tempPath -Force -ErrorAction SilentlyContinue
    exit 1
}

# Clean up temp file
Remove-Item -Path $tempPath -Force -ErrorAction SilentlyContinue

Start-Sleep -Seconds 2

# Verify service was created
$service = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($service) {
    Write-Host "[OK] Service created successfully"
    Write-Host "  Name: $($service.Name)"
    Write-Host "  Status: $($service.Status)"
    Write-Host "  Start Type: $($service.StartType)"

    if ($service.Status -ne "Running") {
        Write-Host "[INFO] Starting service..."
        Start-Service -Name "gururmm-agent"
        Start-Sleep -Seconds 2

        $service = Get-Service -Name "gururmm-agent"
        Write-Host "[OK] Service status: $($service.Status)"
    }
} else {
    Write-Host "[ERROR] Service was not created"
    exit 1
}

Write-Host ""
Write-Host "[SUCCESS] GuruRMM agent with Claude Code integration installed and running!"
