# Fix the remaining PLINK reference to use SSH
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Write-Host "=== Fixing PLINK Usage ===" -ForegroundColor Cyan
Write-Host ""

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    $scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"

    Write-Host "[1] Creating backup" -ForegroundColor Yellow
    $timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
    Copy-Item $scriptPath "$scriptPath.backup-$timestamp"
    Write-Host "[OK] Backup: Sync-FromNAS.ps1.backup-$timestamp" -ForegroundColor Green

    Write-Host ""
    Write-Host "[2] Reading current script" -ForegroundColor Yellow
    $content = Get-Content $scriptPath

    Write-Host "[3] Fixing line 54 (PLINK usage)" -ForegroundColor Yellow

    for ($i = 0; $i -lt $content.Count; $i++) {
        if ($i -eq 53) {  # Line 54 (0-indexed = 53)
            Write-Host "Old: $($content[$i])" -ForegroundColor Red

            # Replace PLINK with SSH and update the command syntax
            $content[$i] = '    $result = & $SSH -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes "$NAS_USER@$NAS_IP" $Command 2>&1'

            Write-Host "New: $($content[$i])" -ForegroundColor Green
        }
    }

    Write-Host ""
    Write-Host "[4] Saving updated script" -ForegroundColor Yellow
    $content | Out-File -FilePath $scriptPath -Encoding UTF8 -Force
    Write-Host "[OK] Script saved" -ForegroundColor Green

    Write-Host ""
    Write-Host "[5] Verifying fix" -ForegroundColor Yellow
    $updatedContent = Get-Content $scriptPath -Raw

    if ($updatedContent -match '\$PLINK') {
        Write-Host "[WARNING] Still found PLINK references!" -ForegroundColor Yellow
    } else {
        Write-Host "[SUCCESS] No PLINK references found" -ForegroundColor Green
    }

    if ($updatedContent -match '\$SSH.*StrictHostKeyChecking') {
        Write-Host "[SUCCESS] SSH command properly configured" -ForegroundColor Green
    }
}

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