# Fix AD2 Sync-FromNAS.ps1 to preserve CRLF line endings
# Add -O flag to SCP commands to use legacy protocol (binary mode)

$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)

Write-Host "[INFO] Connecting to AD2..."

# Read the current script
$ScriptContent = Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
    Get-Content 'C:\Shares\test\scripts\Sync-FromNAS.ps1' -Raw
}

Write-Host "[INFO] Current script retrieved"

# Create backup
$BackupName = "Sync-FromNAS_backup_$(Get-Date -Format 'yyyyMMdd_HHmmss').ps1"
Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
    param($Content, $Backup)
    Set-Content "C:\Shares\test\scripts\$Backup" -Value $Content
} -ArgumentList $ScriptContent, $BackupName

Write-Host "[OK] Backup created: $BackupName"

# Fix the script - Add -O flag to SCP commands
$FixedContent = $ScriptContent -replace '& \$SCP -o StrictHostKeyChecking', '& $SCP -O -o StrictHostKeyChecking'

# Count changes
$Changes = ([regex]::Matches($FixedContent, '-O -o')).Count
Write-Host "[INFO] Adding -O flag to $Changes SCP commands"

# Upload fixed script
Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
    param($Content)
    Set-Content 'C:\Shares\test\scripts\Sync-FromNAS.ps1' -Value $Content
} -ArgumentList $FixedContent

Write-Host "[SUCCESS] Sync-FromNAS.ps1 updated on AD2"
Write-Host ""
Write-Host "[INFO] The -O flag forces legacy SCP protocol (binary mode)"
Write-Host "[INFO] This prevents line ending conversion (CRLF preserved)"
Write-Host ""
Write-Host "Next steps:"
Write-Host "  1. Redeploy DEPLOY.BAT and UPDATE.BAT to AD2"
Write-Host "  2. Wait for next sync cycle (runs every 15 minutes)"
Write-Host "  3. Verify CRLF preserved on NAS"
