# Fix Copy-ToNAS to always log detailed SCP results
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Write-Host "=== Fixing Copy-ToNAS Error Logging ===" -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] Updating Copy-ToNAS function" -ForegroundColor Yellow

    $content = Get-Content $scriptPath

    # Find and replace the Copy-ToNAS function
    $newFunction = @'
function Copy-ToNAS {
    param(
        [string]$LocalPath,
        [string]$RemotePath
    )

    # Ensure remote directory exists
    $remoteDir = Split-Path -Parent $RemotePath
    Invoke-NASCommand "mkdir -p '$remoteDir'" | Out-Null

    $result = & $SCP -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes $LocalPath "${NAS_USER}@${NAS_IP}:$RemotePath" 2>&1

    $exitCode = $LASTEXITCODE

    if ($exitCode -ne 0) {
        # Log detailed error
        $errorMsg = $result | Out-String
        Write-Log "  SCP PUSH ERROR (exit $exitCode): $errorMsg"
    }

    return $exitCode -eq 0
}
'@

    # Find the function start
    $funcStart = -1
    $funcEnd = -1
    $braceCount = 0

    for ($i = 0; $i -lt $content.Count; $i++) {
        if ($content[$i] -match '^function Copy-ToNAS') {
            $funcStart = $i
            continue
        }

        if ($funcStart -ge 0) {
            if ($content[$i] -match '\{') { $braceCount++ }
            if ($content[$i] -match '\}') {
                $braceCount--
                if ($braceCount -eq 0) {
                    $funcEnd = $i
                    break
                }
            }
        }
    }

    if ($funcStart -ge 0 -and $funcEnd -gt $funcStart) {
        Write-Host "[FOUND] Copy-ToNAS function at lines $($funcStart+1)-$($funcEnd+1)" -ForegroundColor Cyan

        # Replace the function
        $newContent = @()
        $newContent += $content[0..($funcStart-1)]
        $newContent += $newFunction
        $newContent += $content[($funcEnd+1)..($content.Count-1)]

        $newContent | Out-File -FilePath $scriptPath -Encoding UTF8 -Force

        Write-Host "[OK] Function updated with enhanced error logging" -ForegroundColor Green
    } else {
        Write-Host "[ERROR] Could not find Copy-ToNAS function boundaries" -ForegroundColor Red
    }

    Write-Host ""
    Write-Host "[3] Verifying update" -ForegroundColor Yellow
    $updatedContent = Get-Content $scriptPath -Raw

    if ($updatedContent -match 'SCP PUSH ERROR.*exit.*exitCode') {
        Write-Host "[SUCCESS] Enhanced error logging is in place" -ForegroundColor Green
    } else {
        Write-Host "[WARNING] Could not verify error logging" -ForegroundColor Yellow
    }
}

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