@echo off
setlocal EnableExtensions EnableDelayedExpansion
title WW.CX Time Setup for Windows

set "SERVER=ntp.ww.cx"
set "PEER=%SERVER%,0x8"

cls
echo ================================================================
echo  WW.CX TIME SETUP FOR WINDOWS
echo ================================================================
echo.
echo This helper configures the built-in Windows Time service to use:
echo   %SERVER%
echo.
echo Protocol: standard NTP over UDP port 123
echo.

rem Require administrator rights. If needed, relaunch this .cmd with UAC.
net session >nul 2>&1
if errorlevel 1 (
    echo Administrator permission is required.
    echo Requesting elevation...
    powershell.exe -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /b
)

echo [1/8] Checking whether this computer is domain joined...
set "DOMAINJOINED=Unknown"
for /f "usebackq delims=" %%D in (`powershell.exe -NoProfile -Command "$c=Get-CimInstance Win32_ComputerSystem; if ($c.PartOfDomain) {'True'} else {'False'}"`) do set "DOMAINJOINED=%%D"

if /i "!DOMAINJOINED!"=="True" (
    echo.
    echo STOP: This computer is joined to an Active Directory domain.
    echo Domain policy normally controls Windows Time and can override manual peers.
    echo Ask the domain administrator before replacing the domain time hierarchy.
    echo.
    pause
    exit /b 3
)

if /i "!DOMAINJOINED!"=="Unknown" (
    echo WARNING: Domain membership could not be determined. Continuing as a standalone computer.
)

echo [2/8] Ensuring the Windows Time service can run...
sc.exe query W32Time >nul 2>&1
if errorlevel 1 (
    echo ERROR: Windows Time service ^(W32Time^) is not installed.
    goto :fail
)

powershell.exe -NoProfile -Command "$s=Get-Service W32Time -ErrorAction Stop; if ($s.StartType -eq 'Disabled') { Set-Service W32Time -StartupType Manual }; if ((Get-Service W32Time).Status -ne 'Running') { Start-Service W32Time }"
if errorlevel 1 (
    echo ERROR: Could not start the Windows Time service.
    goto :fail
)

echo [3/8] Backing up the current Windows Time configuration...
for /f "usebackq delims=" %%T in (`powershell.exe -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"`) do set "STAMP=%%T"
set "BACKUP=%ProgramData%\WWCX-Time\before-!STAMP!"
mkdir "!BACKUP!" >nul 2>&1

w32tm.exe /query /configuration /verbose > "!BACKUP!\w32time-configuration.txt" 2>&1
w32tm.exe /query /peers > "!BACKUP!\w32time-peers.txt" 2>&1
w32tm.exe /query /status > "!BACKUP!\w32time-status.txt" 2>&1
reg.exe export "HKLM\SYSTEM\CurrentControlSet\Services\W32Time" "!BACKUP!\W32Time.reg" /y >nul
if errorlevel 1 (
    echo ERROR: Could not create the W32Time registry backup.
    goto :fail
)

> "!BACKUP!\RESTORE.txt" echo WW.CX Time Setup backup
>>"!BACKUP!\RESTORE.txt" echo.
>>"!BACKUP!\RESTORE.txt" echo Registry backup: W32Time.reg
>>"!BACKUP!\RESTORE.txt" echo To restore the previous registry configuration, import W32Time.reg as Administrator and restart Windows.

echo Backup saved to:
echo   !BACKUP!

echo [4/8] Configuring WW.CX as the Windows NTP peer...
w32tm.exe /config /manualpeerlist:"%PEER%" /syncfromflags:manual /update
if errorlevel 1 (
    echo ERROR: Windows rejected the NTP configuration.
    goto :fail
)

echo [5/8] Restarting Windows Time...
net stop W32Time /y >nul 2>&1
net start W32Time >nul 2>&1
if errorlevel 1 (
    echo ERROR: Windows Time did not restart successfully.
    goto :fail
)

echo [6/8] Asking Windows to rediscover and synchronize...
w32tm.exe /resync /rediscover
if errorlevel 1 (
    echo Initial synchronization did not complete immediately.
    echo Waiting 15 seconds for source discovery, then trying again...
    timeout.exe /t 15 /nobreak >nul
    w32tm.exe /resync
)

timeout.exe /t 5 /nobreak >nul

echo [7/8] Verifying the configured source...
set "SOURCE="
for /f "usebackq delims=" %%S in (`w32tm.exe /query /source 2^>nul`) do set "SOURCE=%%S"

echo.
echo Active source:
echo   !SOURCE!
echo.

reg.exe query "HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Parameters" /v NtpServer | findstr.exe /i /c:"%SERVER%" >nul
if errorlevel 1 (
    echo ERROR: Registry verification did not find %SERVER%.
    goto :fail
)

echo(!SOURCE!| findstr.exe /i /c:"%SERVER%" >nul
if errorlevel 1 (
    echo WARNING: %SERVER% is configured, but Windows is not yet reporting it as the active source.
    echo Windows may need another synchronization interval before switching sources.
) else (
    echo PASS: Windows reports %SERVER% as the active time source.
)

echo.
echo Windows Time status:
w32tm.exe /query /status
echo.
echo Configured peer:
w32tm.exe /query /peers

echo [8/8] Running a direct five-sample WW.CX NTP test...
w32tm.exe /stripchart /computer:%SERVER% /samples:5 /dataonly
if errorlevel 1 (
    echo.
    echo WARNING: The direct NTP test failed. UDP port 123 may be blocked on this network.
    goto :done_with_warning
)

echo.
echo ================================================================
echo  WW.CX TIME SETUP COMPLETE
echo ================================================================
echo Server:    %SERVER%
echo Protocol:  NTP / UDP 123
echo Source:    !SOURCE!
echo Backup:    !BACKUP!
echo.
echo Windows' built-in W32Time client uses standard NTP. It does not
echo use the WW.CX NTS endpoint on TCP port 4460.
echo.
pause
exit /b 0

:done_with_warning
echo.
echo Setup was applied, but one or more verification checks need review.
echo Backup: !BACKUP!
echo.
pause
exit /b 2

:fail
echo.
echo ================================================================
echo  WW.CX TIME SETUP STOPPED
echo ================================================================
echo No further changes will be attempted.
echo If a backup path was shown above, keep it for rollback.
echo.
pause
exit /b 1
