#!/bin/sh

# Usage: monitor-lorawan.sh [-a] [-r] [-d] [gateway]
#   (default) live LoRaWAN uplinks/downlinks from the forwarder log (Semtech UDP or Basic Station)
#   -a        the entire forwarder log
#   -r        raw system log (logread -f)
#   -d        diagnose: processes, log files, config and radio devices
set -eu

password=dragino

# ssh calls this script back as SSH_ASKPASS to read the root password
if [ -n "${MONITOR_LORAWAN_ASKPASS:-}" ]; then
    printf '%s\n' "$password"
    exit 0
fi

mode=lora
while getopts ard opt; do
    case $opt in
        a) mode=all ;;
        r) mode=raw ;;
        d) mode=diag ;;
        *) exit 2 ;;
    esac
done
shift $((OPTIND - 1))
gateway=${1:-10.130.1.1}

case "$gateway" in
    -*|*[^A-Za-z0-9.:_-]*) echo "Invalid gateway: $gateway" >&2; exit 2 ;;
esac

case $mode in
    # Follow whichever forwarder is running: Basic Station logs to station.log, the Semtech UDP forwarder (fwd)
    # to the system log. station.log can be left over after switching to UDP, so check the process, not the file.
    # With the web UI's Record Log on, the whole log since StartLog is in /tmp/logfile.log (max 2 MB). Otherwise only
    # the ~700-line ring buffer remains: logread -l counts lines before filtering and fwd restarts flood it, so
    # replay packets, then follow.
    lora)   cmd='if pidof station >/dev/null; then tail -n 200 -f /var/iot/station.log
             elif [ -e /tmp/logging.flag ]; then tail -n +1 -f /tmp/logfile.log
             else
                 echo "Record Log is off: only recent packets are kept. To keep the full history, open http://'"$gateway"'/cgi-bin/log-record.has" >&2
                 echo "(login root / dragino), go to LogRead > Record Log and click StartLog." >&2
                 logread -e "[rt]xpk"; logread -f -e "[rt]xpk"
             fi' ;;
    all)    cmd='if pidof station >/dev/null; then tail -n 50 -f /var/iot/station.log; else logread -l 50 -f -e fwd; fi' ;;
    raw)    cmd='logread -f' ;;
    diag)   cmd='cat /etc/banner /etc/openwrt_release 2>/dev/null; echo "== processes"; ps | grep -iE "lora|pkt|fwd|station|chirp|mqtt|ttn|tcpdump" | grep -v grep; echo "== log files"; ls -la /var/log /tmp 2>/dev/null; echo "== config"; ls /etc/lora /etc/config 2>/dev/null; uci show gateway 2>/dev/null | head -60; echo "== radio devices"; ls /dev/spidev* /dev/ttyUSB* /dev/ttyACM* 2>&1; echo "== listening"; netstat -lnup 2>/dev/null | head -20' ;;
esac

if ! nc -z -G 3 "$gateway" 22 >/dev/null 2>&1; then
    echo "Cannot reach $gateway on port 22. Join the gateway's WiFi (dragino-xxxxxx) or its LAN, then retry." >&2
    echo "Tip: wired Ethernet routes may override WiFi for 192.168.4.x; unplug Ethernet or run: sudo route add -host $gateway -interface en0" >&2
    exit 1
fi

echo "Connecting to root@$gateway ($mode). Ctrl+C to stop."
SSH_ASKPASS="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
SSH_ASKPASS_REQUIRE=force
MONITOR_LORAWAN_ASKPASS=1
export SSH_ASKPASS SSH_ASKPASS_REQUIRE MONITOR_LORAWAN_ASKPASS
ssh_opts="-o HostKeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa -o ConnectTimeout=10 -o ServerAliveInterval=15"
ssh_cmd="ssh $ssh_opts -tt root@$gateway"
if [ "$mode" = lora ]; then
    # No pty (-T): a pty switches the local terminal to raw mode and garbles the table
    ssh_cmd="ssh $ssh_opts -T root@$gateway"
fi
if [ "$mode" = lora ]; then
    # Format locally: BusyBox on the gateway has no line-buffered grep or python
    $ssh_cmd "$cmd" | python3 -u "$(dirname "$0")/lora_viewer.py"
else
    exec $ssh_cmd "$cmd"
fi
