$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)

Write-Host "Creating SSH wrapper script on AD2..." -ForegroundColor Cyan

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    # Create a local test script that will run SSH without PowerShell remoting overhead
    $testScript = @'
@echo off
REM SSH Test Script - Run locally on AD2
echo Testing SSH from AD2 to NAS...
echo.

echo [1] Testing hostname...
C:\Progra~1\OpenSSH\ssh.exe -o ConnectTimeout=5 -o BatchMode=yes -o StrictHostKeyChecking=no root@192.168.0.9 "hostname"
if %ERRORLEVEL% EQU 0 (
    echo [OK] SSH Works!
) else (
    echo [ERROR] SSH Failed with exit code: %ERRORLEVEL%
)

echo.
echo [2] Testing find command...
C:\Progra~1\OpenSSH\ssh.exe -o ConnectTimeout=10 -o BatchMode=yes -o StrictHostKeyChecking=no root@192.168.0.9 "find /data/test/TS-4R/LOGS -name '*.DAT' -type f 2>/dev/null | head -3"

echo.
echo [3] Running sync script manually...
powershell.exe -ExecutionPolicy Bypass -File "C:\Shares\test\scripts\Sync-FromNAS.ps1"
'@

    $scriptPath = "C:\Temp\test-ssh-local.bat"
    New-Item -Path "C:\Temp" -ItemType Directory -Force | Out-Null
    $testScript | Out-File -FilePath $scriptPath -Encoding ASCII -Force

    Write-Host "[OK] Created test script at: $scriptPath" -ForegroundColor Green
    Write-Host ""
    Write-Host "Now running the script locally..." -ForegroundColor Yellow

    # Run it using Task Scheduler to execute in local context
    $action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c $scriptPath > C:\Temp\ssh-test-output.txt 2>&1"
    $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(5)
    $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries

    Register-ScheduledTask -TaskName "TestSSH-Temp" -Action $action -Trigger $trigger -Settings $settings -User "SYSTEM" -Force | Out-Null

    Write-Host "Waiting for task to complete..." -ForegroundColor Yellow
    Start-Sleep -Seconds 15

    if (Test-Path "C:\Temp\ssh-test-output.txt") {
        Write-Host ""
        Write-Host "========== OUTPUT ==========" -ForegroundColor Cyan
        Get-Content "C:\Temp\ssh-test-output.txt"
        Write-Host "=============================" -ForegroundColor Cyan
    }

    # Cleanup
    Unregister-ScheduledTask -TaskName "TestSSH-Temp" -Confirm:$false -ErrorAction SilentlyContinue
}
