#!/bin/sh
# Alpine 5G Router – full troubleshoot: collect all logs and run diagnostics
# Run on device: /usr/local/bin/troubleshoot-5g.sh
# Or via SSH: ssh root@device /usr/local/bin/troubleshoot-5g.sh
# Rev: 1  (see REVISION in repo root)

CONFIG="/etc/5g-router.conf"
AT_PORT="${AT_PORT:-/dev/ttyUSB1}"
WAN_IF="${WAN_IF:-eth1}"
LOG_FILE="/var/log/5g-router.log"
AT_LOCK="/var/lock/5g-at.lock"

[ -f "$CONFIG" ] && . "$CONFIG" || true

# Acquire lock on AT port so we don't conflict with connect-5g.sh or modem-status-at.sh
exec 9>"$AT_LOCK"
flock -w 15 9 || echo "Warning: could not acquire AT lock (another process using port)"

echo "=============================================="
echo " Alpine 5G Router – Full Troubleshoot"
echo " $(date -Iseconds)"
echo "=============================================="
echo ""

# --- 1) Kernel / USB / tty (recent) ---
echo "--- 1) Kernel messages (dmesg, last 40 lines) ---"
dmesg 2>/dev/null | tail -40 || echo "(dmesg not available)"
echo ""

# --- 2) USB devices ---
echo "--- 2) USB devices (lsusb) ---"
lsusb 2>/dev/null || echo "(lsusb not available)"
if lsusb 2>/dev/null | grep -q "0e8d:7127"; then
    echo "  -> WARN: Modem in Mode 41 (7127). AT port may not work. Need Mode 40 (7126)."
elif lsusb 2>/dev/null | grep -q "0e8d:7126"; then
    echo "  -> Modem in Mode 40 (RNDIS) – OK for AT on ttyUSB1"
fi
echo ""

# --- 3) Serial / AT port nodes ---
echo "--- 3) Serial devices (/dev/ttyUSB[0-9]*, /dev/ttyACM[0-9]*) ---"
if [ -e /dev/ttyUSB ] && [ -f /dev/ttyUSB ] && [ ! -c /dev/ttyUSB ]; then
    echo "  Stray file /dev/ttyUSB (no number) – remove with: rm /dev/ttyUSB"
fi
for d in /dev/ttyUSB0 /dev/ttyUSB1 /dev/ttyUSB2 /dev/ttyUSB3 /dev/ttyUSB4 /dev/ttyUSB5 /dev/ttyACM0 /dev/ttyACM1; do
    [ -e "$d" ] || continue
    ls -la "$d" 2>/dev/null
    if [ -f "$d" ] && [ ! -c "$d" ]; then
        case "$d" in /dev/ttyUSB*) _m=188; _n="${d#/dev/ttyUSB}";; /dev/ttyACM*) _m=166; _n="${d#/dev/ttyACM}";; *) _m=188; _n=0;; esac
        echo "  -> BAD: $d is a regular file. Fix: rm $d && mknod $d c $_m $_n && chmod 660 $d && chown root:dialout $d"
    fi
done
if ! ls /dev/ttyUSB[0-9]* /dev/ttyACM[0-9]* 2>/dev/null | grep -q .; then
    echo "  No ttyUSB/ttyACM devices. Modem may not be bound or not in Mode 40."
fi
echo ""

# --- 4) Config ---
echo "--- 4) Config ($CONFIG) ---"
if [ -f "$CONFIG" ]; then
    grep -E '^[A-Za-z_]+=' "$CONFIG" 2>/dev/null | sed 's/^/  /' || true
else
    echo "  File not found (using defaults: AT_PORT=$AT_PORT, WAN_IF=$WAN_IF)"
fi
echo ""

# --- 5) Processes using the AT port (can block or conflict) ---
echo "--- 5) Processes using $AT_PORT (lsof) ---"
if [ -e "$AT_PORT" ]; then
    if command -v lsof >/dev/null 2>&1; then
        _lsof=$(lsof 2>/dev/null | grep -F "$AT_PORT")
        if [ -n "$_lsof" ]; then
            echo "$_lsof" | sed 's/^/  /'
        else
            echo "  No process has $AT_PORT open (good)"
        fi
    else
        echo "  (lsof not installed – install with: apk add lsof)"
    fi
else
    echo "  Port does not exist (nothing to list)"
fi
echo ""

# --- 6) AT port test (with longer wait like connect-5g.sh) ---
echo "--- 6) AT command test on $AT_PORT (wait 3s) ---"
if [ -c "$AT_PORT" ]; then
    out=$(timeout 8 sh -c "
        [ -c \"$AT_PORT\" ] || exit 1
        cat $AT_PORT 2>/dev/null &
        _p=\$!
        sleep 0.5
        echo -e 'AT\r' > $AT_PORT 2>/dev/null
        sleep 3
        kill \$_p 2>/dev/null
    " 2>&1)
    if echo "$out" | grep -q 'OK'; then
        echo "  AT response: OK (modem responding)"
    else
        echo "  AT response: no OK (modem not responding or wrong port)"
        echo "  Raw output:"
        echo "$out" | head -10 | sed 's/^/    /'
    fi
else
    echo "  $AT_PORT not available (missing or not a character device)"
fi
echo ""

# --- 7) AT probe on all ttyUSB (which port responds) ---
echo "--- 7) AT probe on each ttyUSB port ---"
for port in /dev/ttyUSB0 /dev/ttyUSB1 /dev/ttyUSB2 /dev/ttyUSB3; do
    [ -c "$port" ] || continue
    out=$(timeout 5 sh -c "[ -c \"$port\" ] || exit 1; cat $port 2>/dev/null & _p=\$!; sleep 0.3; echo -e 'AT\r' > $port; sleep 2; kill \$_p 2>/dev/null" 2>/dev/null)
    if echo "$out" | grep -q 'OK'; then
        echo "  $port: OK (use this as AT_PORT if different from config)"
    else
        echo "  $port: no OK"
    fi
done
echo ""

# --- 8) 5g-router service ---
echo "--- 8) 5g-router service ---"
if command -v rc-service >/dev/null 2>&1; then
    rc-service 5g-router status 2>&1 | sed 's/^/  /'
else
    echo "  OpenRC not found"
fi
echo ""

# --- 9) WAN interface and routing ---
echo "--- 9) WAN interface ($WAN_IF) and default route ---"
if ip link show "$WAN_IF" >/dev/null 2>&1; then
    ip link show "$WAN_IF" 2>/dev/null | sed 's/^/  /'
    ip -4 addr show "$WAN_IF" 2>/dev/null | sed 's/^/  /'
else
    echo "  Interface $WAN_IF does not exist"
fi
ip route show default 2>/dev/null | sed 's/^/  /'
echo ""

# --- 10) Full 5g-router log ---
echo "--- 10) Full 5g-router log (last 60 lines of $LOG_FILE) ---"
if [ -f "$LOG_FILE" ]; then
    tail -60 "$LOG_FILE" 2>/dev/null | sed 's/^/  /'
else
    echo "  Log file not found"
fi
echo ""

# --- 11) Optional: modem status script ---
if [ -x "/usr/local/bin/modem-status-at.sh" ]; then
    echo "--- 11) modem-status-at.sh (registration, signal) ---"
    /usr/local/bin/modem-status-at.sh 2>&1 | head -30 | sed 's/^/  /'
else
    echo "--- 11) modem-status-at.sh ---"
    echo "  Not installed"
fi
echo ""

echo "=============================================="
echo " End troubleshoot – copy this output to share"
echo "=============================================="
echo ""
echo "Quick fixes to try:"
echo "  - ttyUSB is regular file: rm $AT_PORT && mknod $AT_PORT c 188 1 && chmod 660 $AT_PORT && chown root:dialout $AT_PORT"
echo "  - Stray /dev/ttyUSB (no number): rm /dev/ttyUSB"
echo "  - Port held by another process (see section 5): stop ModemManager (rc-service ModemManager stop) or restart 5g-router"
echo "  - Modem in Mode 41 (7127): power-cycle modem or reboot; need Mode 40 (7126) for AT"
echo "  - AT not OK: set AT_PORT in $CONFIG to the port that showed OK above (e.g. /dev/ttyUSB0)"
echo "  - Restart connection: service 5g-router restart   or   /usr/local/bin/connect-5g.sh"
