# Invoke-Expression (Invoke-WebRequest -Uri "https://git.technozone.com.au/vijay/Scripts/raw/branch/main/windows_time_sync" -UseBasicP | Select-Object -ExpandProperty Content)

function Show-Menu {
    Clear-Host
    Write-Host "=============================="
    Write-Host " Time Sync Configuration Menu "
    Write-Host "=============================="
    Write-Host "1. Check NTP Server Configuration"
    Write-Host "2. Sync Time with Domain Controller"
    Write-Host "3. Set to Nearest NTP Server"
    Write-Host "4. Check Windows Time Service"
    Write-Host "5. Exit"
}

function Check-NTPConfiguration {
    $ntpServer = Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty DomainRole
    if ($ntpServer -eq 0) {
        Write-Host "This computer is not part of a domain."
    } else {
        $currentNTP = w32tm /query /status | Select-String "Source"
        Write-Host "Current NTP Server: $currentNTP"
    }
    Pause
}

function Sync-TimeWithDC {
    $dc = Read-Host "Enter Domain Controller FQDN or IP Address"
    w32tm /config /manualpeerlist:$dc /syncfromflags:manual /reliable:YES /update
    w32tm /resync
    Write-Host "Time synchronized with $dc."
    Pause
}

function Set-ToNearestNTP {
    w32tm /config /manualpeerlist:"time.windows.com,0x1" /syncfromflags:manual /reliable:YES /update
    w32tm /resync
    Write-Host "Time synchronized with nearest NTP server (time.windows.com)."
    Pause
}

function Check-WindowsTimeService {
    $service = Get-Service w32time
    if ($service.Status -ne 'Running') {
        Write-Host "Windows Time service is not running. Starting the service..."
        Start-Service w32time
        Write-Host "Windows Time service started."
    } else {
        Write-Host "Windows Time service is already running."
    }
    
    # Ensure it's syncing to the nearest time server
    Set-ToNearestNTP
}

do {
    Show-Menu
    $choice = Read-Host "Please enter your choice (1-5)"
    
    switch ($choice) {
        1 { Check-NTPConfiguration }
        2 { Sync-TimeWithDC }
        3 { Set-ToNearestNTP }
        4 { Check-WindowsTimeService }
        5 { Write-Host "Exiting..."; break }
        default { Write-Host "Invalid choice. Please select again." }
    }
} while ($true)
