#!/bin/bash

NTP_SERVER="$1"
MODE="$2"

is_numeric() {
    echo "$1" | grep -qE '^[+-]?[0-9]*\.?[0-9]+$'
}

get_ntp_time_chronyc() {
    drift=$(chronyc tracking 2>/dev/null | awk -F '[: ]+' '/System time/ {gsub(/[-+]/, "", $3); printf "%.2f\n", $3}')
    if [ -n "$drift" ] && is_numeric "$drift"; then
        echo "$drift"
        return 0
    fi
    return 1
}

get_ntp_time_ntpq() {
    drift=$(ntpq -p 2>/dev/null | awk 'NR>2 && $1 ~ /^\*/ {gsub(/[-+]/,"",$9); printf "%.2f\n", $9/1000; exit}')
    if [ -n "$drift" ] && is_numeric "$drift"; then
        echo "$drift"
        return 0
    fi
    return 1
}

get_ntp_time_socket() {
    drift=$(python3 -c "
import socket
import struct
import time

NTP_SERVER = '$NTP_SERVER'
NTP_PORT = 123
NTP_EPOCH = 2208988800

try:
    packet = b'\\x1b' + 47 * b'\\x00'

    local_time = time.time()

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(2)
    sock.sendto(packet, (NTP_SERVER, NTP_PORT))
    data, _ = sock.recvfrom(48)
    sock.close()

    recv_time = time.time()

    seconds = struct.unpack('!I', data[40:44])[0]
    fraction = struct.unpack('!I', data[44:48])[0]

    ntp_time = (seconds - NTP_EPOCH) + (fraction / 2**32)

    round_trip = recv_time - local_time
    ntp_time -= (round_trip / 2)

    drift = ntp_time - local_time
    print('{:.2f}'.format(drift))
except Exception:
    pass
" 2>/dev/null)

    if [ -n "$drift" ] && is_numeric "$drift"; then
        echo "$drift"
        return 0
    fi
    return 1
}

get_ntp_sync_status() {
    sync_status=""

    # Try chronyc first
    if command -v chronyc >/dev/null 2>&1; then
        sync_status=$(chronyc tracking 2>/dev/null | awk -F ': ' '/Leap status/ {print ($2=="Normal")?"Synced":"Not_Synced"}')
    fi

    # Fall back to ntpq
    if [ -z "$sync_status" ]; then
        if command -v ntpq >/dev/null 2>&1; then
            sync_status=$(ntpq -pn 2>/dev/null | awk 'NR>2 && $1 ~ /^\*/ {print "Synced"; found=1; exit} END {if (!found) print "Not_Synced"}')
        fi
    fi

    if [ -n "$sync_status" ]; then
        echo "Data:"
        echo "NTPSyncStatus $sync_status"
        exit 0
    else
        echo "ERROR: Unable to fetch NTPSyncStatus" >&2
        exit 1
    fi
}

# Mode 2: NTP Sync Status check
if [ "$MODE" = "2" ]; then
    get_ntp_sync_status
fi

# Mode 1 (default): NTP Time Drift check
drift_seconds=""

# Try chronyc first
drift_seconds=$(get_ntp_time_chronyc)

# Fall back to ntpq
if [ -z "$drift_seconds" ]; then
    drift_seconds=$(get_ntp_time_ntpq)
fi

# Fall back to direct NTP socket query only if NTP_SERVER is provided
if [ -z "$drift_seconds" ] && [ -n "$NTP_SERVER" ]; then
    drift_seconds=$(get_ntp_time_socket)
fi

if [ -n "$drift_seconds" ]; then
    echo "Data:"
    echo "NTPTimeDrift $drift_seconds"
    exit 0
else
    echo "ERROR: Unable to fetch NTPTimeDrift" >&2
    exit 1
fi