#!/bin/sh
# Programm: ntpstat
# Aufruf: ntpstat or ntpstat last or ntpstat next
# Version: 0.1.0 
# created by jokel 2026

MODE="$1"

tracking=$(chronyc tracking)
sources=$(chronyc sources)

# Leap-Status
leap=$(echo "$tracking" | grep "Leap status" | awk '{print $4}')

# Ref time (UTC)
ref_time=$(echo "$tracking" | grep "Ref time" | cut -d: -f2- | sed 's/^ *//')

# Ref time zerlegen
set -- $ref_time
day=$3
time=$4
year=$5

case "$2" in
  Jan) month=01 ;; Feb) month=02 ;; Mar) month=03 ;; Apr) month=04 ;;
  May) month=05 ;; Jun) month=06 ;; Jul) month=07 ;; Aug) month=08 ;;
  Sep) month=09 ;; Oct) month=10 ;; Nov) month=11 ;; Dec) month=12 ;;
esac

ref_iso="$year-$month-$day $time"

# UTC -> Epoch
last_sync_epoch=$(date -u -d "$ref_iso" +%s)
now_epoch=$(date +%s)

# Age berechnen
age=$(( now_epoch - last_sync_epoch ))

# Lokale Zeit anzeigen
last_sync_local=$(date -d "@$last_sync_epoch" +"%Y-%m-%d %H:%M:%S")

# *** aktive Quelle richtig finden ***
active=$(echo "$sources" | grep '^\^\*')

if [ -z "$active" ]; then
	echo "ERROR: keine aktive Quelle gefunden"
	echo "$sources"
	exit 1
fi

# Symbol (^*) entfernen
active_trimmed=$(echo "$active" | sed 's/^.. //')

# Hostname entfernen -> übrig: Stratum Poll Reach LastRx ...
active_trimmed=$(echo "$active_trimmed" | sed 's/^[^ ]* //')

# Poll & LastRx extrahieren
poll=$(echo "$active_trimmed" | awk '{print $2}')
lastrx=$(echo "$active_trimmed" | awk '{print $4}')

# Falls Poll oder LastRx leer -> fallback
[ -z "$poll" ] && poll=10
[ -z "$lastrx" ] && lastrx=0

# echtes Intervall
interval=$(( 1 << poll ))

# Zeit bis zum nächsten Poll
remaining=$(( interval - lastrx ))
[ $remaining -lt 0 ] && remaining=0

next_sync_epoch=$(( now_epoch + remaining ))
#next_sync_human=$(date -d "@$next_sync_epoch")
next_sync_human=$(date -d "@$next_sync_epoch" +"%Y-%m-%d %H:%M:%S")

# Kurzmodus: nur "last" oder "next"
if [ "$MODE" = "last" ]; then
	echo "$last_sync_local"	 "offset:" $(echo "$tracking" | grep "System time" | awk '{print $4, $5}')
	exit 0
fi

if [ "$MODE" = "next" ]; then
	echo "$next_sync_human"
	exit 0
fi

# Ausgabe
if [ "$leap" = "Normal" ]; then
	echo "synchronised"
else
	echo "unsynchronised"
fi

echo "Last sync : $last_sync_local"
echo "Age		: ${age}s"
echo "Poll		: $poll"
echo "Interval	: ${interval}s"
echo "LastRx	: ${lastrx}s"
echo "Next sync : $next_sync_human"
echo "Remaining : ${remaining}s"

offset=$(echo "$tracking" | grep "System time" | awk '{print $4, $5, $6}')
echo "Offset	: $offset"

