param(
    [Parameter(Mandatory=$true, Position=0)]
    [string]$NTPServer,

    [Parameter(Mandatory=$true, Position=1)]
    [ValidateSet("1","2")]
    [string]$CheckType
)

function Is-Numeric {
    param($Value)
    return $Value -match "^\+*\-*[\d\.]+$"
}

function Get-NtpTime {
    param([string]$NTPServer)

    try {
        # Build NTP request packet. We'll reuse this variable for the response packet
        $NTPData = New-Object byte[] 48 # Array of 48 bytes set to zero
        $NTPData[0] = 27 # Request header: 00 = No Leap Warning; 011 = Version 3; 011 = Client Mode;00011011 = 27

        $localTime = ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()) / 1000
        $timer = [Diagnostics.Stopwatch]::StartNew()

        $socket = New-Object Net.Sockets.Socket('InterNetwork','Dgram','Udp')
        $socket.SendTimeout = 2000
        $socket.ReceiveTimeout = 2000
        $socket.Connect($NTPServer,123)

        # Make the request
        $null = $socket.Send($NTPData)
        $null = $socket.Receive($NTPData)

        $timer.Stop()
        # Clean up the connection
        $Socket.Shutdown('Both')
        $socket.Close()

        # Extract relevant portion of first date in result (Number of seconds since "Start of Epoch")
        $seconds = [BitConverter]::ToUInt32($NTPData[43..40],0)
        $fraction = [BitConverter]::ToUInt32($NTPData[47..44],0)

        # Add them to the "Start of Epoch", convert to unix epoch
        $seconds -= (([datetime]'1970-01-01') - ([datetime]'1900-01-01')).TotalSeconds
        $fraction = $fraction / [math]::Pow(2,32)

        $ntpTime = $seconds + $fraction
        $ntpTime -= ($timer.ElapsedMilliseconds / 2000)

        return ($ntpTime - $localTime)   # seconds
    }
    catch {
        throw "Direct NTP query failed"
    }
}

if ($CheckType -eq "1") {
    # NTP Time Drift monitoring
    try {
        $ntpQuery = w32tm /monitor /computers:$NTPServer 2>&1 | Out-String
        $regex = [regex]"NTP:\s*(?<offset>[-+]?\d+(\.\d+)?)s"

        if ($ntpQuery -match $regex) {
            $driftSeconds = $Matches['offset']
            if (-not (Is-Numeric $driftSeconds)) {
                throw "Invalid drift from w32tm"
            }
        }
        else {
            $driftSeconds = Get-NtpTime -NTPServer $NTPServer
        }
        $timedrift = [Math]::Round([Math]::Abs($driftSeconds))
        Write-Output "Data:"
        Write-Output "NTPTimeDrift $timedrift"
        exit 0
    }
    catch {
        Write-Error "ERROR: Unable to fetch NTPTimeDrift from $NTPServer"
        exit 1
    }
}
elseif ($CheckType -eq "2") {
    # NTP Sync Status monitoring
    try {
        $ntpQuery = w32tm /monitor /computers:$NTPServer 2>&1 | Out-String

        if ($ntpQuery -match "NTP:\s*[-+]?\d+(\.\d+)?s") {
            $syncStatus = "Synced"
        }
        else {
            $syncStatus = "Not_Synced"
        }

        Write-Output "Data:"
        Write-Output "NTPSyncStatus $syncStatus"
        exit 0
    }
    catch {
        Write-Error "ERROR: Unable to fetch NTPSyncStatus from $NTPServer"
        exit 1
    }
}