# Fix the known_hosts path issue in Sync-FromNAS.ps1
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Write-Host "=== Fixing Known Hosts Path ===" -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 created: Sync-FromNAS.ps1.backup-$timestamp" -ForegroundColor Green

    Write-Host ""
    Write-Host "[2] Ensuring .ssh directory exists" -ForegroundColor Yellow
    $sshDir = "C:\Shares\test\scripts\.ssh"
    if (-not (Test-Path $sshDir)) {
        New-Item -Path $sshDir -ItemType Directory -Force | Out-Null
        Write-Host "[OK] Created: $sshDir" -ForegroundColor Green
    } else {
        Write-Host "[OK] Directory exists: $sshDir" -ForegroundColor Green
    }

    Write-Host ""
    Write-Host "[3] Updating SCP commands with absolute path" -ForegroundColor Yellow

    $content = Get-Content $scriptPath
    $updated = $false

    for ($i = 0; $i -lt $content.Count; $i++) {
        # Look for SCP commands with UserKnownHostsFile parameter
        if ($content[$i] -match 'UserKnownHostsFile="\$SCRIPTS_DIR\\.ssh\\known_hosts"') {
            # Replace with absolute path
            $content[$i] = $content[$i] -replace 'UserKnownHostsFile="\$SCRIPTS_DIR\\.ssh\\known_hosts"', 'UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts"'
            Write-Host "[UPDATED] Line $($i+1): Changed to absolute path" -ForegroundColor Green
            $updated = $true
        }
    }

    if ($updated) {
        $content | Out-File -FilePath $scriptPath -Encoding UTF8 -Force
        Write-Host "[OK] Script updated with absolute path" -ForegroundColor Green
    } else {
        Write-Host "[INFO] No changes needed - path already absolute" -ForegroundColor Yellow
    }

    Write-Host ""
    Write-Host "[4] Creating initial known_hosts file" -ForegroundColor Yellow

    $knownHostsPath = "C:\Shares\test\scripts\.ssh\known_hosts"

    # Get NAS host key if not already present
    if (-not (Test-Path $knownHostsPath)) {
        Write-Host "[INFO] Creating new known_hosts file" -ForegroundColor Cyan
        # Create empty file - StrictHostKeyChecking=accept-new will add keys automatically
        New-Item -Path $knownHostsPath -ItemType File -Force | Out-Null
        Write-Host "[OK] Created: $knownHostsPath" -ForegroundColor Green
    } else {
        $keyCount = (Get-Content $knownHostsPath | Measure-Object -Line).Lines
        Write-Host "[OK] Exists with $keyCount host key(s)" -ForegroundColor Green
    }

    Write-Host ""
    Write-Host "[5] Testing SCP with fixed path" -ForegroundColor Yellow
    Write-Host "=== Testing a single file transfer ===" -ForegroundColor Gray

    # Create a test file
    $testFile = "C:\Shares\test\scripts\scp-test-$(Get-Date -Format 'yyyyMMddHHmmss').txt"
    "SCP Test from AD2 at $(Get-Date)" | Out-File $testFile

    $result = & "C:\Program Files\OpenSSH\scp.exe" -v `
        -o StrictHostKeyChecking=accept-new `
        -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" `
        -o PreferredAuthentications=password `
        -o PubkeyAuthentication=no `
        -o PasswordAuthentication=yes `
        $testFile "admin@192.168.0.9:/volume1/test/scp-test.txt" 2>&1

    if ($LASTEXITCODE -eq 0) {
        Write-Host "[SUCCESS] SCP test transfer completed!" -ForegroundColor Green
        Write-Host "[OK] Host key added to known_hosts" -ForegroundColor Green
        Remove-Item $testFile -Force
    } else {
        Write-Host "[ERROR] SCP test failed (exit code: $LASTEXITCODE)" -ForegroundColor Red
        Write-Host "Output:" -ForegroundColor Yellow
        $result | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    }
}

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