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

Write-Host "================================================" -ForegroundColor Cyan
Write-Host "Fixing SSH Agent on AD2" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
Write-Host ""

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    Write-Host "[1/4] Starting SSH Agent service..." -ForegroundColor Yellow
    try {
        Set-Service ssh-agent -StartupType Automatic
        Start-Service ssh-agent
        Write-Host "  [OK] SSH Agent started" -ForegroundColor Green
    } catch {
        Write-Host "  [ERROR] Failed to start SSH Agent: $($_.Exception.Message)" -ForegroundColor Red
    }

    Start-Sleep -Seconds 2

    Write-Host ""
    Write-Host "[2/4] Adding private key to agent..." -ForegroundColor Yellow
    $keyFile = "$env:USERPROFILE\.ssh\id_ed25519"
    $sshAdd = & "C:\Program Files\OpenSSH\ssh-add.exe" $keyFile 2>&1
    Write-Host "  Result: $sshAdd" -ForegroundColor White

    Write-Host ""
    Write-Host "[3/4] Verifying key is loaded..." -ForegroundColor Yellow
    $sshList = & "C:\Program Files\OpenSSH\ssh-add.exe" -l 2>&1
    Write-Host "  Loaded keys: $sshList" -ForegroundColor White

    Write-Host ""
    Write-Host "[4/4] Testing SSH connection now..." -ForegroundColor Yellow
    try {
        $env:SSH_AUTH_SOCK = (Get-Service ssh-agent | Get-ItemProperty -Name ImagePath).ImagePath
        $result = cmd /c "echo | C:\Progra~1\OpenSSH\ssh.exe -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 hostname 2>&1"
        if ($LASTEXITCODE -eq 0) {
            Write-Host "  [OK] SSH CONNECTION SUCCESSFUL: $result" -ForegroundColor Green
        } else {
            Write-Host "  [ERROR] SSH still failing: $result" -ForegroundColor Red
        }
    } catch {
        Write-Host "  [ERROR] Exception: $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "SSH Agent Fix Complete" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
