#!/bin/sh
# Alpine 5G Router – status (modem, interface, default route, last speedtest)
# Usage: status-5g.sh [--json] (optional machine-readable output)
# Rev: 1  (see REVISION in repo root)

CONFIG="/etc/5g-router.conf"
WAN_IF="${WAN_IF:-eth1}"
LAN_IF="${LAN_IF:-eth0.100}"
AT_PORT="${AT_PORT:-/dev/ttyUSB1}"
[ -f "$CONFIG" ] && . "$CONFIG"

SPEEDTEST_LOG="/var/log/speedtest-5g.log"
MODEM_USB=$(lsusb 2>/dev/null | grep -i fibocom | head -1)
DEFAULT_ROUTE=$(ip route show default 2>/dev/null | head -1)
WAN_IP=$(ip -4 addr show "$WAN_IF" 2>/dev/null | grep -oE 'inet [0-9.]+' | awk '{print $2}')
WAN_STATE=$(ip link show "$WAN_IF" 2>/dev/null | grep -oE 'state [A-Z]+' | awk '{print $2}')
LAST_SPEEDTEST=""
[ -f "$SPEEDTEST_LOG" ] && LAST_SPEEDTEST=$(tail -5 "$SPEEDTEST_LOG" 2>/dev/null)

if [ "$1" = "--json" ]; then
    echo "{"
    echo "  \"modem_usb\": \"${MODEM_USB:-none}\","
    echo "  \"wan_interface\": \"$WAN_IF\","
    echo "  \"wan_state\": \"${WAN_STATE:-unknown}\","
    echo "  \"wan_ip\": \"${WAN_IP:-}\","
    echo "  \"default_route\": \"${DEFAULT_ROUTE:-none}\","
    echo "  \"at_port\": \"$AT_PORT\","
    echo "  \"at_available\": \"$([ -c \"$AT_PORT\" ] && echo yes || echo no)\""
    echo "}"
    exit 0
fi

echo "=== 5G Router Status ==="
echo "Modem:    ${MODEM_USB:-not detected}"
echo "AT port:  $AT_PORT ($([ -c "$AT_PORT" ] && echo "available" || echo "not available"))"
echo "WAN:      $WAN_IF state=$WAN_STATE ip=$WAN_IP"
echo "Default:  $DEFAULT_ROUTE"
echo ""
echo "--- Last speedtest ---"
if [ -n "$LAST_SPEEDTEST" ]; then
    echo "$LAST_SPEEDTEST"
else
    echo "(none – run speedtest-cli --simple and redirect to $SPEEDTEST_LOG)"
fi
