# Fix the sync functions more precisely
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Write-Host "=== Fixing Sync Script Functions ===" -ForegroundColor Cyan
Write-Host ""

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

    Write-Host "[1] Finding Copy-FromNAS function" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

    # Find the function
    for ($i = 0; $i -lt $content.Count; $i++) {
        if ($content[$i] -match "^function Copy-FromNAS") {
            Write-Host "Found at line $($i+1): $($content[$i])" -ForegroundColor Green

            # Show the function (next 10 lines)
            Write-Host "Current function:" -ForegroundColor Cyan
            for ($j = $i; $j -lt ($i + 10) -and $j -lt $content.Count; $j++) {
                Write-Host "  $($j+1): $($content[$j])" -ForegroundColor Gray
            }
            break
        }
    }

    Write-Host ""
    Write-Host "[2] Finding Copy-ToNAS function" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

    for ($i = 0; $i -lt $content.Count; $i++) {
        if ($content[$i] -match "^function Copy-ToNAS") {
            Write-Host "Found at line $($i+1): $($content[$i])" -ForegroundColor Green

            # Show the function (next 10 lines)
            Write-Host "Current function:" -ForegroundColor Cyan
            for ($j = $i; $j -lt ($i + 10) -and $j -lt $content.Count; $j++) {
                Write-Host "  $($j+1): $($content[$j])" -ForegroundColor Gray
            }
            break
        }
    }

    Write-Host ""
    Write-Host "[3] Creating updated script with OpenSSH" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

    # Create new script content with line-by-line replacement
    $newContent = @()
    $inCopyFromNAS = $false
    $inCopyToNAS = $false
    $funcDepth = 0

    for ($i = 0; $i -lt $content.Count; $i++) {
        $line = $content[$i]

        # Track when we enter functions
        if ($line -match "^function Copy-FromNAS") {
            $inCopyFromNAS = $true
            $funcDepth = 0
            $newContent += "function Copy-FromNAS {"
            $newContent += "    param([string]`$RemotePath, [string]`$LocalPath)"
            $newContent += ""
            $newContent += "    # OpenSSH scp with verbose logging"
            $newContent += "    `$result = & `$SCP -v -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=`"`$SCRIPTS_DIR\.ssh\known_hosts`" `"`${NAS_USER}@`${NAS_IP}:`$RemotePath`" `$LocalPath 2>&1"
            $newContent += ""
            $newContent += "    if (`$LASTEXITCODE -ne 0) {"
            $newContent += "        Write-Log `"  SCP PULL ERROR: `$(`$result | Out-String)`""
            $newContent += "    }"
            $newContent += ""
            $newContent += "    return `$LASTEXITCODE -eq 0"
            $newContent += "}"
            # Skip until we find the closing brace
            continue
        }

        if ($line -match "^function Copy-ToNAS") {
            $inCopyToNAS = $true
            $funcDepth = 0
            $newContent += "function Copy-ToNAS {"
            $newContent += "    param([string]`$LocalPath, [string]`$RemotePath)"
            $newContent += ""
            $newContent += "    # OpenSSH scp with verbose logging"
            $newContent += "    `$result = & `$SCP -v -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=`"`$SCRIPTS_DIR\.ssh\known_hosts`" `$LocalPath `"`${NAS_USER}@`${NAS_IP}:`$RemotePath`" 2>&1"
            $newContent += ""
            $newContent += "    if (`$LASTEXITCODE -ne 0) {"
            $newContent += "        Write-Log `"  SCP PUSH ERROR: `$(`$result | Out-String)`""
            $newContent += "    }"
            $newContent += ""
            $newContent += "    return `$LASTEXITCODE -eq 0"
            $newContent += "}"
            # Skip until we find the closing brace
            continue
        }

        # Track braces when inside function
        if ($inCopyFromNAS -or $inCopyToNAS) {
            if ($line -match "{") { $funcDepth++ }
            if ($line -match "}") {
                $funcDepth--
                if ($funcDepth -le 0) {
                    # End of function, stop skipping
                    $inCopyFromNAS = $false
                    $inCopyToNAS = $false
                }
            }
            # Skip lines inside the old function
            continue
        }

        # Update tool paths
        if ($line -match '\$PSCP\s*=') {
            $newContent += '$SCP = "C:\Program Files\OpenSSH\scp.exe"'
            continue
        }
        if ($line -match '\$PLINK\s*=') {
            $newContent += '$SSH = "C:\Program Files\OpenSSH\ssh.exe"'
            continue
        }

        # Keep all other lines
        $newContent += $line
    }

    # Save the updated script
    $newContent | Out-File -FilePath $scriptPath -Encoding UTF8 -Force

    Write-Host "[OK] Script updated with OpenSSH functions" -ForegroundColor Green
    Write-Host "[OK] Saved: $scriptPath" -ForegroundColor Green
}

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