#!/bin/bash
set -euo pipefail
source "$(dirname "$0")/lib.sh"

log "Configuring gpsd for /dev/gps..."

# /etc/default/gpsd
sudo tee /etc/default/gpsd >/dev/null <<EOF
START_DAEMON="true"
DEVICES="/dev/gps"
USBAUTO="true"
GPSD_OPTIONS="-n"
EOF

sudo systemctl enable gpsd
sudo systemctl restart gpsd || warn "gpsd restart failed — is /dev/gps present?"

log "Merging GPS refclock into chrony..."

CHRONY_CONF="/etc/chrony/chrony.conf"
MARKER="# --- HamPi GPS refclock ---"

if grep -q "HamPi GPS refclock" "$CHRONY_CONF" 2>/dev/null; then
    warn "HamPi chrony block already present — not duplicating"
else
    {
        echo ""
        echo "$MARKER"
        cat "${ROOT}/configs/chrony-gps.conf"
    } | sudo tee -a "$CHRONY_CONF" >/dev/null
    log "Appended GPS refclock + allow directives to chrony.conf"
fi

sudo systemctl enable chrony
sudo systemctl restart chrony

log "GPS + chrony step complete"
echo "  Test: cgps -s"
echo "  Test: chronyc sources -v"
echo "  After hours of runtime, tune 'offset' in chrony.conf using chronyc sourcestats"
