#!/bin/sh
# Alpine 5G Router – AT port diagnostic (run on device to debug “No modem AT data”)
# Rev: 1  (see REVISION in repo root)
# Usage: ./diag-at-port.sh   or   /usr/local/bin/diag-at-port.sh

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

echo "=== Alpine 5G Router – AT port diagnostic ==="
echo ""

# 1) User and permissions
echo "--- User & groups ---"
echo "User: $(id -un) (uid=$(id -u) gid=$(id -g))"
echo "Groups: $(id -Gn)"
if id -Gn | grep -q dialout; then
    echo "dialout: YES (can access serial ports)"
else
    echo "dialout: NO – add user to dialout: adduser <user> dialout"
fi
echo ""

# 2) Serial devices
echo "--- Serial devices ---"
for d in /dev/ttyUSB* /dev/ttyACM*; do
    [ -e "$d" ] || continue
    ls -la "$d" 2>/dev/null
done
if ! ls /dev/ttyUSB* /dev/ttyACM* 2>/dev/null | grep -q .; then
    echo "No /dev/ttyUSB* or /dev/ttyACM* found. Modem may not be in USB mode 40 or not bound."
fi
echo ""

# 3) Modem USB
echo "--- Modem (lsusb) ---"
lsusb 2>/dev/null | grep -i fibocom || echo "No Fibocom device in lsusb"
lsusb 2>/dev/null | grep -i "0e8d" || true
echo ""

# 4) Config
echo "--- Config ---"
echo "AT_PORT from config: $AT_PORT"
if [ -c "$AT_PORT" ]; then
    echo "  -> exists and is a character device"
else
    echo "  -> missing or not a character device"
fi
echo ""

# 5) Raw AT probe on each ttyUSB
echo "--- Raw AT probe (send AT, show response) ---"
for port in /dev/ttyUSB0 /dev/ttyUSB1 /dev/ttyUSB2 /dev/ttyUSB3; do
    [ -c "$port" ] || continue
    echo "Port $port:"
    out=$(timeout 4 sh -c "
        cat $port 2>/dev/null &
        _p=\$!
        sleep 0.3
        echo -e 'AT\r' > $port 2>/dev/null
        sleep 1
        kill \$_p 2>/dev/null
    " 2>/dev/null)
    if echo "$out" | grep -q 'OK'; then
        echo "  -> OK (modem responded)"
    else
        echo "  -> no OK in response (raw below)"
    fi
    echo "$out" | head -5 | sed 's/^/  /'
    echo ""
done
if ! ls /dev/ttyUSB* 2>/dev/null | grep -q .; then
    echo "No ttyUSB devices to probe."
fi
echo ""

# 6) modem-status-at.sh if present
echo "--- modem-status-at.sh ---"
if [ -x "/usr/local/bin/modem-status-at.sh" ]; then
    echo "Running: /usr/local/bin/modem-status-at.sh"
    out=$(timeout 20 /usr/local/bin/modem-status-at.sh 2>&1)
    code=$?
    echo "Exit code: $code"
    echo "$out" | head -15
    if [ "$code" != 0 ] || echo "$out" | grep -q '^{}$'; then
        echo "... (no modem JSON or script failed)"
    fi
else
    echo "Not found at /usr/local/bin/modem-status-at.sh (install with scripts/install.sh)"
fi
echo ""
echo "=== End diagnostic ==="
