# Fix the missing line break on line 92
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Write-Host "=== Fixing Line Break Issue ===" -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 script" -ForegroundColor Yellow
    $content = Get-Content $scriptPath

    Write-Host ""
    Write-Host "[3] Fixing line 92" -ForegroundColor Yellow
    Write-Host "Before:" -ForegroundColor Red
    Write-Host "  $($content[91])" -ForegroundColor Red

    # Split line 92 at the "if" keyword
    if ($content[91] -match '^(.+2>&1)\s+(if.+)$') {
        $scpLine = $matches[1]
        $ifLine = "    $($matches[2])"

        Write-Host ""
        Write-Host "After:" -ForegroundColor Green
        Write-Host "  $scpLine" -ForegroundColor Green
        Write-Host "  $ifLine" -ForegroundColor Green

        # Replace line 91 (0-indexed) with the SCP line and insert the if line
        $newContent = @()
        for ($i = 0; $i -lt $content.Count; $i++) {
            if ($i -eq 91) {
                $newContent += $scpLine
                $newContent += $ifLine
            } else {
                $newContent += $content[$i]
            }
        }

        Write-Host ""
        Write-Host "[4] Saving fixed script" -ForegroundColor Yellow
        $newContent | 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

        Write-Host "Lines 92-95:" -ForegroundColor Cyan
        for ($i = 91; $i -le 94; $i++) {
            Write-Host "  $($i+1): $($updatedContent[$i])" -ForegroundColor Gray
        }

    } else {
        Write-Host "[ERROR] Could not parse line 92" -ForegroundColor Red
        Write-Host "Line content: $($content[91])" -ForegroundColor Yellow
    }
}

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