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

Write-Host "================================================" -ForegroundColor Cyan
Write-Host "Sync Diagnostic Report" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
Write-Host ""

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    Write-Host "[1] Checking Sync Task Status..." -ForegroundColor Yellow
    $task = Get-ScheduledTask -TaskName "Sync-FromNAS" -ErrorAction SilentlyContinue
    if ($task) {
        Write-Host "  State: $($task.State)" -ForegroundColor White
        $taskInfo = Get-ScheduledTaskInfo -TaskName "Sync-FromNAS"
        Write-Host "  Last Run: $($taskInfo.LastRunTime)" -ForegroundColor White
        Write-Host "  Last Result: 0x$($taskInfo.LastTaskResult.ToString('X'))" -ForegroundColor White
        Write-Host "  Next Run: $($taskInfo.NextRunTime)" -ForegroundColor White
    }
    Write-Host ""

    Write-Host "[2] Checking for Running Sync Processes..." -ForegroundColor Yellow
    $syncProcs = Get-Process -Name pwsh,powershell -ErrorAction SilentlyContinue |
        Where-Object { $_.CommandLine -like "*Sync-FromNAS*" }
    if ($syncProcs) {
        Write-Host "  Found $($syncProcs.Count) running sync process(es)" -ForegroundColor Red
        $syncProcs | ForEach-Object {
            Write-Host "    PID $($_.Id): Started $($_.StartTime)" -ForegroundColor White
        }
    } else {
        Write-Host "  No sync processes running" -ForegroundColor Green
    }
    Write-Host ""

    Write-Host "[3] Checking commonSources Configuration..." -ForegroundColor Yellow
    $syncScript = Get-Content "C:\Shares\test\scripts\Sync-FromNAS.ps1" -Raw
    if ($syncScript -match '\$commonSources\s*=\s*@\((.*?)\)') {
        Write-Host "  Found commonSources config:" -ForegroundColor White
        Write-Host $matches[0] -ForegroundColor Gray
    }
    Write-Host ""

    Write-Host "[4] Last 10 Sync Log Entries..." -ForegroundColor Yellow
    if (Test-Path "C:\Shares\test\scripts\sync-from-nas.log") {
        Get-Content "C:\Shares\test\scripts\sync-from-nas.log" | Select-Object -Last 10 |
            ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    }
    Write-Host ""

    Write-Host "[5] Testing SSH Connection to NAS..." -ForegroundColor Yellow
    $sshTest = ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 "echo OK" 2>&1
    if ($sshTest -eq "OK") {
        Write-Host "  SSH connection: OK" -ForegroundColor Green
    } else {
        Write-Host "  SSH connection: FAILED - $sshTest" -ForegroundColor Red
    }
}

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