#Requires -Version 5.1


# Use -ShutdownRegardless to force shutdown even if one or more sync jobs fail.
param(
    [switch]$ShutdownRegardless
)

$FfsExe    = 'C:\Program Files\FreeFileSync\FreeFileSync.exe'
$ScriptDir = $PSScriptRoot
$LogDir    = Join-Path $ScriptDir 'logs'
$ReportDir = Join-Path $ScriptDir 'reports'

$SyncJobs = @(
    'C:\sync_jobs\shuttlebay_SyncSettings.ffs_batch'
    'C:\sync_jobs\main_bridge_SyncSettings.ffs_batch'
    'C:\sync_jobs\engineering_SyncSettings.ffs_batch'
)

# ── Setup ──────────────────────────────────────────────────────────────────────
foreach ($dir in $LogDir, $ReportDir) {
    if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null }
}

$RunTs   = Get-Date -Format 'yyyyMMdd_HHmmss'
$LogFile = Join-Path $LogDir "sync_history_$RunTs.log"

function Write-Log {
    param([string]$Message)
    $line = "[$(Get-Date -Format 'ddd MM/dd/yyyy HH:mm:ss.ff')] $Message"
    Write-Host $line
    Add-Content -Path $LogFile -Value $line
}

Write-Log 'Sync run started'
Write-Host "Log file: $LogFile"

# ── Run sync jobs ──────────────────────────────────────────────────────────────
$HadFatalError = $false
$FatalExitCodes = @()

foreach ($job in $SyncJobs) {
    $jobName = Split-Path $job -Leaf
    Write-Host ''
    Write-Log "Running synchronization: $jobName"

    $tmpOut = [IO.Path]::GetTempFileName()
    $proc = Start-Process -FilePath $FfsExe -ArgumentList $job `
                -RedirectStandardOutput $tmpOut -NoNewWindow -PassThru -Wait
    $rc = $proc.ExitCode
    $output = Get-Content -Path $tmpOut -Raw
    Remove-Item $tmpOut -Force
    if ($output) { Add-Content -Path $LogFile -Value $output }

    switch ($rc) {
        0 { Write-Log 'Synchronization completed successfully.' }
        1 { Write-Log 'Synchronization completed with warnings.' }
        default {
            Write-Log "Synchronization failed or was aborted. Exit code: $rc"
            $HadFatalError = $true
            $FatalExitCodes += $rc
            continue
        }
    }
}

Write-Host ''
Write-Log 'All synchronization jobs completed.'

# ── Copy HTML reports ──────────────────────────────────────────────────────────
$logPaths = Select-String -Path $LogFile -Pattern '"logFile"\s*:\s*"([^"]+)"' |
    ForEach-Object { $_.Matches[0].Groups[1].Value -replace '\\\\', '\' } |
    Sort-Object -Unique

$copied = 0
foreach ($path in $logPaths) {
    if ([IO.Path]::GetExtension($path) -ieq '.html') {
        if (Test-Path -LiteralPath $path) {
            Copy-Item -LiteralPath $path -Destination $ReportDir -Force
            Write-Log "Copied report: $(Split-Path $path -Leaf)"
            $copied++
        } else {
            Write-Log "Report not found: $path"
        }
    }
}

Write-Log "Total reports copied: $copied"

# ── Shutdown ───────────────────────────────────────────────────────────────────
if ($HadFatalError) {
    $codes = ($FatalExitCodes | Sort-Object -Unique) -join ', '
    Write-Log "One or more synchronization jobs failed. Fatal exit code(s): $codes"

    if (-not $ShutdownRegardless) {
        Write-Log 'Skipping shutdown because not all synchronization jobs completed successfully.'
        Write-Log 'Use -ShutdownRegardless to force shutdown even when jobs fail.'
        exit ($FatalExitCodes | Select-Object -Last 1)
    }

    Write-Log 'Forced shutdown enabled. Continuing to shutdown despite synchronization failures.'
}

Write-Log 'Shutting down server now.'
Invoke-CimMethod -ClassName Win32_OperatingSystem -MethodName Win32Shutdown -Arguments @{ Flags = 5 }
