# Update Sync-FromNAS.ps1 to use OpenSSH with verbose logging
# This will show us the actual errors that are happening

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

Write-Host "=== Updating Sync Script to Use OpenSSH ===" -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] Reading current sync script" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

    $content = Get-Content $scriptPath -Raw

    Write-Host "[OK] Script loaded ($($content.Length) characters)" -ForegroundColor Green
    Write-Host ""

    Write-Host "[2] Updating to use OpenSSH" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

    # Replace PuTTY paths with OpenSSH paths
    $content = $content -replace '\$PSCP\s*=\s*"[^"]*pscp\.exe"', '$SCP = "C:\Program Files\OpenSSH\scp.exe"'
    $content = $content -replace '\$PLINK\s*=\s*"[^"]*plink\.exe"', '$SSH = "C:\Program Files\OpenSSH\ssh.exe"'

    Write-Host "[OK] Replaced tool paths (PuTTY -> OpenSSH)" -ForegroundColor Green

    # Update Copy-FromNAS function to use OpenSSH with verbose logging
    $oldCopyFrom = @'
function Copy-FromNAS {
    param([string]$RemotePath, [string]$LocalPath)

    $result = & $PSCP -ssh -pw $NAS_PASSWORD -hostkey $NAS_HOSTKEY "${NAS_USER}@${NAS_IP}:$RemotePath" $LocalPath 2>&1
    return $LASTEXITCODE -eq 0
}
'@

    $newCopyFrom = @'
function Copy-FromNAS {
    param([string]$RemotePath, [string]$LocalPath)

    # OpenSSH scp with password auth and verbose logging
    $env:SSHPASS = $NAS_PASSWORD
    $result = & $SCP -v -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$SCRIPTS_DIR\.ssh\known_hosts" "${NAS_USER}@${NAS_IP}:$RemotePath" $LocalPath 2>&1

    if ($LASTEXITCODE -ne 0) {
        Write-Log "  SCP PULL ERROR: $($result | Out-String)"
    }

    return $LASTEXITCODE -eq 0
}
'@

    $content = $content -replace [regex]::Escape($oldCopyFrom), $newCopyFrom

    # Update Copy-ToNAS function to use OpenSSH with verbose logging
    $oldCopyTo = @'
function Copy-ToNAS {
    param([string]$LocalPath, [string]$RemotePath)

    $result = & $PSCP -ssh -pw $NAS_PASSWORD -hostkey $NAS_HOSTKEY $LocalPath "${NAS_USER}@${NAS_IP}:$RemotePath" 2>&1
    return $LASTEXITCODE -eq 0
}
'@

    $newCopyTo = @'
function Copy-ToNAS {
    param([string]$LocalPath, [string]$RemotePath)

    # OpenSSH scp with password auth and verbose logging
    $env:SSHPASS = $NAS_PASSWORD
    $result = & $SCP -v -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$SCRIPTS_DIR\.ssh\known_hosts" $LocalPath "${NAS_USER}@${NAS_IP}:$RemotePath" 2>&1

    if ($LASTEXITCODE -ne 0) {
        Write-Log "  SCP PUSH ERROR: $($result | Out-String)"
    }

    return $LASTEXITCODE -eq 0
}
'@

    $content = $content -replace [regex]::Escape($oldCopyTo), $newCopyTo

    # Check if we found and replaced the functions
    if ($content -like "*OpenSSH scp*") {
        Write-Host "[OK] Updated Copy-FromNAS and Copy-ToNAS functions" -ForegroundColor Green
    } else {
        Write-Host "[WARNING] Functions may not have been updated - check manually" -ForegroundColor Yellow
    }

    Write-Host ""
    Write-Host "[3] Saving updated script" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

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

    Write-Host "[OK] Script saved: $scriptPath" -ForegroundColor Green
    Write-Host ""

    Write-Host "[4] Next sync will use OpenSSH and log detailed errors" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray
    Write-Host "The next sync run (every 15 minutes) will:" -ForegroundColor White
    Write-Host "  - Use native OpenSSH tools (scp instead of pscp)" -ForegroundColor Cyan
    Write-Host "  - Log verbose output with -v flag" -ForegroundColor Cyan
    Write-Host "  - Show actual error messages in sync-from-nas.log" -ForegroundColor Cyan
    Write-Host "  - Auto-accept host keys (StrictHostKeyChecking=accept-new)" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "Check the log after next sync:" -ForegroundColor Yellow
    Write-Host "  Get-Content C:\Shares\test\scripts\sync-from-nas.log -Tail 50" -ForegroundColor Gray
}

Write-Host ""
Write-Host "=== Script Update Complete ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "1. Wait for next scheduled sync (runs every 15 minutes)" -ForegroundColor White
Write-Host "2. Check logs for detailed error messages" -ForegroundColor White
Write-Host "3. The actual pscp errors will now be visible!" -ForegroundColor White
