# Test script to run ON AD2 - diagnoses NAS SSH hang issue
$SSH = "C:\Program Files\OpenSSH\ssh.exe"
$SSH_KEY = "C:\Users\sysadmin\.ssh\id_ed25519"
$NAS_USER = "root"
$NAS_IP = "192.168.0.9"

Write-Host "=== Step 1: Kill any hung SSH processes ==="
Get-Process ssh -ErrorAction SilentlyContinue | ForEach-Object {
    Write-Host "  Killing SSH PID $($_.Id)"
    Stop-Process -Id $_.Id -Force
}
Get-Process powershell -ErrorAction SilentlyContinue | Where-Object { $_.Id -ne $PID } | ForEach-Object {
    Write-Host "  Other PowerShell PID $($_.Id) - CommandLine: $($_.CommandLine)"
}

Write-Host "`n=== Step 2: Basic SSH echo test ==="
$t1 = Get-Date
$r1 = & $SSH -i $SSH_KEY -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${NAS_USER}@${NAS_IP}" "echo NAS_OK" 2>&1
$d1 = (Get-Date) - $t1
Write-Host "  Result: $r1 (took $($d1.TotalSeconds)s)"

Write-Host "`n=== Step 3: find with temp file redirect (the actual fix) ==="
$t2 = Get-Date
Write-Host "  Running find with output to /tmp/test-list.txt..."
# This is exactly what Get-NASFileList does - output goes to file on NAS, stdout discarded
& $SSH -i $SSH_KEY -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${NAS_USER}@${NAS_IP}" "find /data/test/TS-*/LOGS -name '*.DAT' -type f -mmin -1440 > /tmp/test-list.txt 2>/dev/null" *> $null
$d2 = (Get-Date) - $t2
Write-Host "  SSH returned in $($d2.TotalSeconds)s"

Write-Host "`n=== Step 4: Count files found ==="
$r3 = & $SSH -i $SSH_KEY -o BatchMode=yes -o ConnectTimeout=10 "${NAS_USER}@${NAS_IP}" "wc -l /tmp/test-list.txt; head -3 /tmp/test-list.txt" 2>&1
foreach ($line in $r3) { Write-Host "  $line" }

Write-Host "`n=== Step 5: Pull file list via SCP ==="
$localTemp = "$env:TEMP\test-nas-filelist.txt"
& "C:\Program Files\OpenSSH\scp.exe" -O -i $SSH_KEY -o StrictHostKeyChecking=accept-new "${NAS_USER}@${NAS_IP}:/tmp/test-list.txt" "$localTemp" *> $null
if (Test-Path $localTemp) {
    $lines = Get-Content $localTemp | Where-Object { $_.Trim() -ne '' }
    Write-Host "  Downloaded $($lines.Count) file paths"
    Remove-Item $localTemp -ErrorAction SilentlyContinue
} else {
    Write-Host "  ERROR: SCP failed to download file"
}

Write-Host "`n=== Step 6: Cleanup ==="
& $SSH -i $SSH_KEY -o BatchMode=yes -o ConnectTimeout=10 "${NAS_USER}@${NAS_IP}" "rm -f /tmp/test-list.txt" 2>&1 | Out-Null

Write-Host "`n=== DONE ==="
