#!/usr/bin/env bash
# time_check.sh — NTP synchronization status and clock drift.
set -euo pipefail

DRIFT_S=0
SYNCED=true

if command -v chronyc >/dev/null 2>&1; then
  TRACKING=$(chronyc tracking 2>/dev/null || true)
  DRIFT_NS=$(echo "$TRACKING" | awk '/System time/ {print $4}' | sed 's/-//' || echo "0")
  DRIFT_S=$(awk "BEGIN {printf \"%.6f\", $DRIFT_NS/1e9}")
  # chronyc returns a very small value when synced (nanoseconds)
elif command -v timedatectl >/dev/null 2>&1; then
  STATUS=$(timedatectl show 2>/dev/null || true)
  if echo "$STATUS" | grep -q "NTPSynchronized=no"; then
    SYNCED=false
  fi
fi

if ! $SYNCED; then
  echo '{"health":"degraded","signalKind":"time-drift","evidence":"NTP not synchronized"}'
elif [ "$(echo "$DRIFT_S > 1" | bc 2>/dev/null || echo 0)" = "1" ]; then
  echo "{\"health\":\"degraded\",\"signalKind\":\"time-drift\",\"evidence\":\"clock drift ${DRIFT_S}s exceeds 1s threshold\",\"metrics\":{\"clock_drift_s\":$DRIFT_S}}"
else
  echo "{\"health\":\"healthy\",\"metrics\":{\"clock_drift_s\":$DRIFT_S}}"
fi
