#!/bin/sh
# Alpine 5G Router – health check for monitoring (Nagios, Uptime Kuma, etc.)
# Exit 0 = OK, 1 = 5G down or no connectivity
# Usage: healthcheck-5g.sh [--ping-only]
# Rev: 1  (see REVISION in repo root)

CONFIG="/etc/5g-router.conf"
WAN_IF="${WAN_IF:-eth1}"
[ -f "$CONFIG" ] && . "$CONFIG"

PING_TARGET="${PING_TARGET:-8.8.8.8}"

# Check default route goes via 5G
def_if=$(ip route show default 2>/dev/null | awk '{print $5}' | head -1)
if [ "$def_if" != "$WAN_IF" ]; then
    echo "CRITICAL: default route not via $WAN_IF (got: $def_if)"
    exit 1
fi

# Check WAN has an address
wan_ip=$(ip -4 addr show "$WAN_IF" 2>/dev/null | grep -oE 'inet [0-9.]+' | awk '{print $2}')
if [ -z "$wan_ip" ]; then
    echo "CRITICAL: no IP on $WAN_IF"
    exit 1
fi

if [ "$1" = "--ping-only" ]; then
    if ping -c 1 -W 3 "$PING_TARGET" >/dev/null 2>&1; then
        echo "OK: ping $PING_TARGET"
        exit 0
    else
        echo "CRITICAL: ping $PING_TARGET failed"
        exit 1
    fi
fi

# Full check: route + ping
if ping -c 2 -W 5 "$PING_TARGET" >/dev/null 2>&1; then
    echo "OK: 5G up, ping $PING_TARGET"
    exit 0
else
    echo "CRITICAL: 5G route OK but ping $PING_TARGET failed"
    exit 1
fi
