#!/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="https://www.pcio.dk/wp-json/boat-position/v1/ingest"
API_KEY="sk83dddgg5dgjss"

QUEUE_DIR="/tmp/gpsqueue"
mkdir -p "$QUEUE_DIR"

# 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 "$TIME No valid GPS fix (mode=$FIX), skipping."
exit 1
fi

[ -z "$COURSE" ] && COURSE="0"
[ -z "$SPEED" ] && SPEED="0"

#
# Store request as its own file
#
ID=$(date -u +"%Y%m%d%H%M%S")
TMPFILE="$QUEUE_DIR/${ID}_$$.tmp"
MSGFILE="$QUEUE_DIR/${ID}_$$.req"

cat > "$TMPFILE" </dev/null | sort)
do
HTTP_CODE=$(curl \
-s \
-o /dev/null \
-w "%{http_code}" \
--connect-timeout 10 \
--max-time 30 \
-X POST "$URL" \
--data-binary @"$FILE")

if [ "$HTTP_CODE" = "200" ]; then
echo "$(date -u +"%Y-%m-%dT%H:%M:%SZ") Sent $(basename "$FILE")"
rm -f "$FILE"
else
echo "$(date -u +"%Y-%m-%dT%H:%M:%SZ") Send failed (HTTP $HTTP_CODE)"
break
fi
done