# Investigate Dataforth Sync Errors on AD2
Write-Host "=== Investigating Dataforth Sync Errors ===" -ForegroundColor Cyan
Write-Host ""

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

Write-Host "Connecting to AD2 and analyzing sync logs..." -ForegroundColor Yellow
Write-Host ""

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    $logFile = "C:\Shares\test\scripts\sync-from-nas.log"
    $statusFile = "C:\Shares\test\_SYNC_STATUS.txt"

    Write-Host "[1] Current Sync Status" -ForegroundColor Yellow
    Write-Host "=" * 60 -ForegroundColor Gray
    if (Test-Path $statusFile) {
        Get-Content $statusFile
    } else {
        Write-Host "Status file not found" -ForegroundColor Red
    }
    Write-Host ""

    Write-Host "[2] Log File Information" -ForegroundColor Yellow
    Write-Host "=" * 60 -ForegroundColor Gray
    if (Test-Path $logFile) {
        $file = Get-Item $logFile
        Write-Host "File: $($file.FullName)" -ForegroundColor White
        Write-Host "Size: $([math]::Round($file.Length / 1MB, 2)) MB" -ForegroundColor White
        Write-Host "Last Modified: $($file.LastWriteTime)" -ForegroundColor White
        Write-Host "Lines: $((Get-Content $logFile).Count)" -ForegroundColor White
    } else {
        Write-Host "Log file not found: $logFile" -ForegroundColor Red
        return
    }
    Write-Host ""

    Write-Host "[3] Analyzing Errors (last 1000 lines)" -ForegroundColor Yellow
    Write-Host "=" * 60 -ForegroundColor Gray

    # Read last 1000 lines to analyze recent errors
    $recentLines = Get-Content $logFile -Tail 1000

    # Count error types
    $errors = $recentLines | Select-String -Pattern "ERROR|Error|error|FAIL|Failed|failed"
    $warnings = $recentLines | Select-String -Pattern "WARNING|Warning|warning"

    Write-Host "Total Error Lines (last 1000): $($errors.Count)" -ForegroundColor $(if ($errors.Count -gt 0) { "Red" } else { "Green" })
    Write-Host "Total Warning Lines (last 1000): $($warnings.Count)" -ForegroundColor $(if ($warnings.Count -gt 0) { "Yellow" } else { "Green" })
    Write-Host ""

    if ($errors.Count -gt 0) {
        Write-Host "[4] Error Breakdown" -ForegroundColor Yellow
        Write-Host "=" * 60 -ForegroundColor Gray

        # Analyze common error patterns
        $errorPatterns = @{
            "No such file" = "No such file|not found|cannot find"
            "Permission denied" = "Permission denied|Access denied|Access is denied"
            "Connection" = "Connection|connect|timeout"
            "File in use" = "being used|in use|locked"
            "SSH/SCP" = "ssh|scp|plink|pscp"
        }

        foreach ($pattern in $errorPatterns.Keys) {
            $count = ($errors | Select-String -Pattern $errorPatterns[$pattern]).Count
            if ($count -gt 0) {
                Write-Host "  $pattern`: $count" -ForegroundColor Red
            }
        }
        Write-Host ""

        Write-Host "[5] Sample Errors (last 15)" -ForegroundColor Yellow
        Write-Host "=" * 60 -ForegroundColor Gray
        $errors | Select-Object -Last 15 | ForEach-Object {
            # Remove timestamp and show just the error
            $line = $_.Line -replace '^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s+:\s+', ''
            Write-Host "  $line" -ForegroundColor Red
        }
        Write-Host ""
    }

    Write-Host "[6] Recent Sync Activity (last 10 operations)" -ForegroundColor Yellow
    Write-Host "=" * 60 -ForegroundColor Gray
    $recentLines | Select-String -Pattern "Pushed:|Pulled:|Deleted:" | Select-Object -Last 10 | ForEach-Object {
        Write-Host "  $($_.Line)" -ForegroundColor Gray
    }
    Write-Host ""

    Write-Host "[7] Today's Summary" -ForegroundColor Yellow
    Write-Host "=" * 60 -ForegroundColor Gray
    $today = Get-Date -Format "yyyy-MM-dd"
    $todayLines = $recentLines | Where-Object { $_ -like "*$today*" }

    if ($todayLines) {
        $todayPush = ($todayLines | Select-String -Pattern "Pushed:").Count
        $todayPull = ($todayLines | Select-String -Pattern "Pulled:").Count
        $todayDelete = ($todayLines | Select-String -Pattern "Deleted:").Count
        $todayErrors = ($todayLines | Select-String -Pattern "ERROR|Error|error|FAIL").Count

        Write-Host "  Files Pushed: $todayPush" -ForegroundColor Green
        Write-Host "  Files Pulled: $todayPull" -ForegroundColor Green
        Write-Host "  Files Deleted: $todayDelete" -ForegroundColor Cyan
        Write-Host "  Errors: $todayErrors" -ForegroundColor $(if ($todayErrors -gt 0) { "Red" } else { "Green" })
    } else {
        Write-Host "  No activity logged for today ($today)" -ForegroundColor Yellow
    }
    Write-Host ""

    Write-Host "[8] Script Status" -ForegroundColor Yellow
    Write-Host "=" * 60 -ForegroundColor Gray
    $scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
    if (Test-Path $scriptPath) {
        $script = Get-Item $scriptPath
        Write-Host "  Script: $($script.Name)" -ForegroundColor White
        Write-Host "  Last Modified: $($script.LastWriteTime)" -ForegroundColor White

        # Check if scheduled task exists
        $task = Get-ScheduledTask -TaskName "Sync-FromNAS" -ErrorAction SilentlyContinue
        if ($task) {
            Write-Host "  Scheduled Task: Enabled" -ForegroundColor Green
            Write-Host "  Task Status: $($task.State)" -ForegroundColor White
            Write-Host "  Last Run: $($task.LastRunTime)" -ForegroundColor White
            Write-Host "  Next Run: $($task.NextRunTime)" -ForegroundColor White
        } else {
            Write-Host "  Scheduled Task: Not found" -ForegroundColor Red
        }
    }
}

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