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

Write-Host "Fixing Sync Script SSH Commands..." -ForegroundColor Cyan

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    $scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
    $backupPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1.backup-$(Get-Date -Format 'yyyyMMdd-HHmmss')"

    Write-Host "[1] Backing up current script..." -ForegroundColor Yellow
    Copy-Item $scriptPath $backupPath
    Write-Host "  Backup: $backupPath" -ForegroundColor Green

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

    Write-Host ""
    Write-Host "[3] Adding SSH key parameter to all SSH/SCP commands..." -ForegroundColor Yellow
    $sshKeyPath = "$env:USERPROFILE\.ssh\id_ed25519"

    # Replace ssh commands to include -i flag
    $content = $content -replace 'ssh\s+root@', "ssh -i `"$sshKeyPath`" -o BatchMode=yes -o ConnectTimeout=10 root@"
    # Replace scp commands to include -i flag
    $content = $content -replace 'scp\s+', "scp -i `"$sshKeyPath`" -o BatchMode=yes -o ConnectTimeout=10 "

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

    Write-Host ""
    Write-Host "[5] Verifying changes (showing first SSH command)..." -ForegroundColor Yellow
    $content | Select-String "ssh -i" | Select-Object -First 3 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
}
