#!/bin/sh
# sendgps.sh — Send the current GPS position to the boat-position API.
# Designed for Teltonika RUTX50 (RutOS / OpenWrt).
#
# Setup on the router:
#   1. Copy this file to /home/root/sendgps.sh
#   2. chmod +x /home/root/sendgps.sh
#   3. Add a cron job (System -> Administration -> Cron):
#        */1 * * * * /home/root/sendgps.sh >> /tmp/sendgps.log 2>&1
#
# The site URL and API key below are filled in automatically when you
# download this script from the plugin's "About" page.

URL="{{INGEST_URL}}"
API_KEY="{{API_KEY}}"

# Read the current GPS fix from gpsd via ubus
GPS=$(ubus call gpsd position)

LAT=$(echo "$GPS"    | jsonfilter -e '@.latitude')
LON=$(echo "$GPS"    | jsonfilter -e '@.longitude')
SPEED=$(echo "$GPS"  | jsonfilter -e '@.speed_vtg_knots')
COURSE=$(echo "$GPS" | jsonfilter -e '@.angle')
FIX=$(echo "$GPS"    | jsonfilter -e '@.fix_curr_mode')

# Timestamp in true UTC from the router's (NTP-synced) system clock.
# Do NOT use the GPS receiver's local time here — it has no offset and would
# be stored as if it were UTC, throwing the live view off by the timezone.
TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Require at least a 2D fix before sending
if [ -z "$FIX" ] || [ "$FIX" -lt 2 ]; then
    echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) No valid GPS fix (mode=$FIX), skipping."
    exit 1
fi

# Default missing optional fields
[ -z "$COURSE" ] && COURSE="0"
[ -z "$SPEED" ]  && SPEED="0"

curl -s -X POST "$URL" \
  -d "apikey=$API_KEY" \
  -d "lat=$LAT" \
  -d "lon=$LON" \
  -d "speed=$SPEED" \
  -d "course=$COURSE" \
  -d "gps_time=$TIME"
