#!/bin/sh
# Busrouter telemetry — BusyBox-compatible. Posts device state to fleet hub.
HUB="http://167.172.237.162:8080/api/telemetry"
ID=$(cat /etc/busrouter/device-id 2>/dev/null || hostname)
TS=$(date +%s)
UP=$(awk '{printf "%d", $1}' /proc/uptime 2>/dev/null)

# BusyBox grep doesn't have -P; use sed instead
WAN1=$(ip -4 addr show eth0 2>/dev/null | sed -n 's/.*inet \([0-9.]*\).*/\1/p' | head -1)
WAN2=$(ip -4 addr show eth2 2>/dev/null | sed -n 's/.*inet \([0-9.]*\).*/\1/p' | head -1)
GW=$(ip route show default 2>/dev/null | sed -n 's/.*via \([0-9.]*\).*/\1/p' | head -1)

# Build JSON with proper escaping for BusyBox
cat >/tmp/telemetry.json <<EOF
{"device_id":"$ID","platform":"synology","timestamp":$TS,"uptime":$UP,"version":"0.1-0001","wan":{"wan1":{"ip":"$WAN1"},"wan2":{"ip":"$WAN2"},"gateway":"$GW"}}
EOF

curl -s --connect-timeout 5 --max-time 10 -X POST "$HUB" \
  -H "Content-Type: application/json" \
  -d @/tmp/telemetry.json >/dev/null 2>&1
rm -f /tmp/telemetry.json
