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

Write-Host "Fixing Sync Script to Use SSH Keys..." -ForegroundColor Cyan

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

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

    Write-Host "[2] Removing password authentication options..." -ForegroundColor Yellow

    # Remove all the password auth options and replace with key auth
    $content = $content -replace '-o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes', ''

    # Add SSH key to Invoke-NASCommand function
    $content = $content -replace '(\$SSH -o StrictHostKeyChecking)', '$$SSH -i "C:\Users\sysadmin\.ssh\id_ed25519" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking'

    Write-Host "[3] Writing fixed script..." -ForegroundColor Yellow
    $content | Out-File $scriptPath -Encoding UTF8 -Force
    Write-Host "  [OK] Script updated to use SSH keys" -ForegroundColor Green

    Write-Host ""
    Write-Host "[4] Showing fixed Invoke-NASCommand..." -ForegroundColor Yellow
    $content | Select-String -Pattern "Invoke-NASCommand" -Context 0,5 | Select-Object -First 1
}
