# ==============================
# Windows Time Sync - Smart MSP Version
# ==============================

function Ensure-Admin {
    if (-not ([Security.Principal.WindowsPrincipal] `
        [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
        [Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Write-Host "❌ Please run as Administrator!" -ForegroundColor Red
        exit
    }
}

function Restart-TimeService {
    Stop-Service w32time -Force -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 2
    Start-Service w32time
}

function Repair-TimeService {
    Write-Host "🛠 Repairing Windows Time Service..." -ForegroundColor Yellow

    Stop-Service w32time -Force -ErrorAction SilentlyContinue
    w32tm /unregister
    Start-Sleep -Seconds 2
    w32tm /register
    Start-Service w32time
}

function Test-DomainReachable {
    try {
        $domain = (Get-CimInstance Win32_ComputerSystem).Domain
        if ($domain -eq $env:COMPUTERNAME) {
            return $false
        }

        nltest /dsgetdc:$domain > $null 2>&1
        return $LASTEXITCODE -eq 0
    } catch {
        return $false
    }
}

function Sync-Domain {
    Write-Host "🏢 Attempting Domain Sync..." -ForegroundColor Cyan

    w32tm /config /syncfromflags:domhier /update
    Restart-TimeService

    w32tm /resync /rediscover

    Start-Sleep -Seconds 3
}

function Sync-PublicNTP {
    Write-Host "🌏 Falling back to AU NTP servers..." -ForegroundColor Yellow

    $ntpServers = "0.au.pool.ntp.org,0x1 1.au.pool.ntp.org,0x1 2.au.pool.ntp.org,0x1"

    w32tm /config /manualpeerlist:"$ntpServers" /syncfromflags:manual /reliable:NO /update

    Restart-TimeService

    w32tm /resync

    Start-Sleep -Seconds 3
}

function Force-HardTimeFix {
    Write-Host "💥 Applying HARD fallback (manual correction)..." -ForegroundColor Red

    try {
        $ntp = "0.au.pool.ntp.org"

        $data = w32tm /stripchart /computer:$ntp /samples:1 /dataonly |
            Select-String ".*"

        $time = ($data -split ',')[1].Trim()

        if ($time) {
            Set-Date -Date $time
            Write-Host "✅ Time corrected from NTP server"
        } else {
            throw "No time received"
        }
    } catch {
        Write-Host "❌ Hard correction failed"
    }
}

function Validate-Time {
    $source = (w32tm /query /source)

    if ($source -match "Local CMOS Clock") {
        return $false
    }
    return $true
}

function Show-Status {
    Write-Host "`n📊 Current Time Status:" -ForegroundColor Green
    w32tm /query /status
    Write-Host ""
    w32tm /query /source
}

# ==============================
# MAIN
# ==============================

Ensure-Admin

Write-Host "=============================="
Write-Host " Smart Time Sync Engine"
Write-Host "==============================`n"

Repair-TimeService

$domainOK = Test-DomainReachable

if ($domainOK) {
    Sync-Domain
} else {
    Write-Host "❌ Domain NOT reachable — switching to NTP" -ForegroundColor Red
    Sync-PublicNTP
}

# Validate
if (-not (Validate-Time)) {
    Write-Host "⚠ Still not syncing — retrying with NTP..." -ForegroundColor Yellow
    Sync-PublicNTP
}

# Final fallback
if (-not (Validate-Time)) {
    Force-HardTimeFix
}

Show-Status

Write-Host "`n✅ Time sync process completed." -ForegroundColor Green