#!/bin/sh
# mu300-dash-info -- the dashboard's system/network snapshot: ONE line of JSON on stdout.
#
# The LuCI home page (luci-app-mu300) polls this through the rpcd backend
# /usr/libexec/rpcd/mu300dash every few seconds. It reads only files and asks
# ubus/uci/iw, so it never touches the modem's AT channel - the cell readings
# live in mu300-dash-cell, which has its own cache and its own pace.
#
# CPU time and interface byte counters are "since boot" cumulative values; the
# page subtracts two consecutive snapshots to get CPU% and live rates, so the
# poll interval never skews the numbers.
#
# Every external call is wrapped in a hard timeout: netifd mid-reload or a wedged
# driver must not void the whole snapshot (the same lesson the V50 panel learned
# in the field - one hung call used to blank every readout on the page).
#
# Known traps this deliberately works around (docs/FINDINGS.md and the V50
# research archive):
#   * loadavg is meaningless here - three vendor kernel threads sit in D state
#     and pin it around 3.5 forever. It is not reported at all.
#   * iw/iwinfo never report tx-power or a sane channel on the sprd WCN driver;
#     SSID/channel come from uci instead.
#   * thermal zones are matched by type, never by zone number.

export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/libexec/unisoc-modem:/usr/sbin:/sbin"
# the shared JSON escaper and uci allow-lists (/usr/share/unisoc-modem/lib.sh)
LIB=${0%/*}/../../share/unisoc-modem/lib.sh
[ -f "$LIB" ] || LIB=/usr/share/unisoc-modem/lib.sh
. "$LIB"

BB=/opt/mu300/bin/busybox
[ -x "$BB" ] || BB=busybox
t3() { "$BB" timeout -s KILL 3 "$@" 2>/dev/null; }   # external asks: netifd, uci, iw...
t2() { "$BB" timeout -s KILL 2 "$@" 2>/dev/null; }

rd() { cat "$1" 2>/dev/null; }
# numbers and strings through the shared helpers (lib.sh): host names, SSIDs
# and the APN come from other people's devices and from uci
n_or_null() { json_num "$1"; }
f_or_null() { json_num "$1"; }
qs() { json_str_or_null "$1"; }

# ------------------------------------------------------------- temperature
# type -> label, the four zones this SoC actually has; hottest covers the rest
temp_of() {
    local z t
    for z in /sys/class/thermal/thermal_zone*; do
        [ -r "$z/type" ] || continue
        [ "$(rd "$z/type")" = "$1" ] || continue
        t=$(rd "$z/temp")
        [ -n "$t" ] || return 0
        awk -v v="$t" 'BEGIN{printf "%.1f", v/1000}'
        return 0
    done
}
temp_hottest() {
    rd /sys/class/thermal/thermal_zone*/temp 2>/dev/null | sort -n | tail -n1 | awk '{printf "%.1f", $1/1000}'
}

# ------------------------------------------------------- a ubus scalar field
# the ubus CLI pretty-prints with spaces, so sed on the literal key; first match
# wins (the fields used here appear once, ipv4 before ipv6 in the address blocks)
jval() { printf '%s' "$1" | sed -n "s/.*\"$2\": *\"\{0,1\}\([^,\"}\]*\).*/\1/p" | head -n1; }

# ----------------------------------------------------------------- WAN (ubus)
# the UI can write these options: interface names only (they become ubus
# object names, /sys paths and uci keys), else the defaults
cfg() { uci_get "$1"; }
DATA_IFACE=$(safe_iface "$(cfg data_interface)" wan)
DATA_IFACE6=$(safe_iface "$(cfg data_interface_v6)" wan6)
WANJSON=$(t3 ubus call "network.interface.$DATA_IFACE" status)
WAN6JSON=$(t3 ubus call "network.interface.$DATA_IFACE6" status)
SIM_SLOT=0
# The SIM selector's own account, for the pages (issue #194): "slot" the card this boot uses, "wanted" the one the
# configuration asks for, "slot1_supported" whether this device has the internal card at all. mu300-sim falls back to
# slot 0 on a device without slot 1, and nothing said so: the home page and the interface page read it from here.
# Local only (uci and a file under /run): no AT command. null without the selector, when status fails, or when
# the U30 transaction reports active:null. A pinned routing slot is not proof of an observed active card.
SIMBIN=${MU300_SIM_BIN:-/opt/mu300/bin/mu300-sim}
SIM_JSON=null
if [ -x "$SIMBIN" ]; then
    SIM_SLOT=$("$SIMBIN" active) || exit 1
    sim_status=$("$SIMBIN" status --json 2>/dev/null)
    sim_n() { printf '%s\n' "$sim_status" | sed -n "s/.*\"$1\": *\([0-9]\).*/\1/p" | head -n1; }
    sim_active=$(sim_n active); sim_wanted=$(sim_n default); sim_s1=$(sim_n slot1_supported)
    case "$sim_active$sim_wanted$sim_s1" in
        [12][12][01]) SIM_JSON="{\"slot\":$((sim_active - 1)),\"wanted\":$((sim_wanted - 1)),\"slot1_supported\":$sim_s1}" ;;
    esac
    # the ZTE V50 (FINDINGS 204): slot 0 is built-in SIM 1 or the external SIM, slot 1 built-in SIM 2 or 3
    case $SIM_JSON:$sim_status in '{'*:*'"v50":{'*) SIM_JSON="${SIM_JSON%\}},\"v50\":1}" ;; esac
fi
# The mobile data device: the one netifd's WAN uses now (its l3_device) first, the configured one (data_device) while the
# WAN has none, the slot's CID 1 bearer last. A configured name used to win over the live one, so a WAN on another
# device (another CID, the other card's bearer after a live switch) was counted on the wrong interface.
DATA_DEVICE=$(safe_iface "$(jval "$WANJSON" l3_device)" '')
[ -n "$DATA_DEVICE" ] || DATA_DEVICE=$(safe_iface "$(cfg data_device)" '')
[ -n "$DATA_DEVICE" ] || DATA_DEVICE=sipa_eth$((SIM_SLOT * 8))
LAN_DEVICE=$(safe_iface "$(cfg lan_device)" br-lan)
WIFI_DEVICE=$(safe_iface "$(cfg wifi_device)" wlan0)
USB_DEVICE=$(safe_iface "$(cfg usb_device)" usb0)
jaddr4() { printf '%s' "$1" | sed -n 's/.*"address": *"\([^"]*\)".*/\1/p' | head -n1; }
# The active DNS servers of the data interfaces. ubus pretty-prints the array over several lines, so it is read with
# jsonfilter: the top-level "dns-server" only (never inactive.dns-server), IPv4 and IPv6 status alike, each server
# once. Based on kanoqwq/mu300-linux@5c8c2f9.
wan_dns_servers() {
    local snapshot
    for snapshot in "$@"; do
        [ -n "$snapshot" ] || continue
        jsonfilter -s "$snapshot" -e '@["dns-server"][*]' 2>/dev/null || :
    done | awk 'NF && !seen[$0]++ { printf "%s%s", sep, $0; sep = ", " }'
}

wan_up=$(jval "$WANJSON" up)
[ "$wan_up" = "true" ] && wan_up=1 || wan_up=0
wan_uptime=$(jval "$WANJSON" uptime)
wan_proto=$(jval "$WANJSON" proto)
wan_ip4=$(jaddr4 "$WANJSON")
wan6_up=$(jval "$WAN6JSON" up)
[ "$wan6_up" = "true" ] && wan6_up=1 || wan6_up=0
wan6_ip=$(t2 ip -6 addr show "$DATA_DEVICE" 2>/dev/null | awk '/inet6 [23]/{split($2,s,"/"); print s[1]; exit}')
wan_dns=$(wan_dns_servers "$WANJSON" "$WAN6JSON")
# slot 1 (the F50's internal card) has its own APN option, see mu300cell.sh
apn_option=apn
[ "$SIM_SLOT" != 1 ] || apn_option=apn_internal
apn=$(t3 uci -q get "network.$DATA_IFACE.$apn_option")
[ -n "$apn" ] || apn="(SIM default)"
# data roaming (mobile-data, docs/FINDINGS.md 120): the card's setting - unset or anything but a "no" is allowed, as
# the dial reads it - and whether data is held back because the card is registered as roaming
roam_option=roaming
[ "$SIM_SLOT" != 1 ] || roam_option=roaming_internal
case $(t3 uci -q get "network.$DATA_IFACE.$roam_option") in 0|off|no|false) roam_allowed=0 ;; *) roam_allowed=1 ;; esac
roam_held=0
[ ! -e "${MU300_ROAM_HELD:-/run/mu300/data-roaming-held}" ] || roam_held=1

# ------------------------------------------------------------------- system
NOW=$(date +%s)
UPTIME=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)
HOST=$(t3 uci -q get system.@system[0].hostname)
[ -n "$HOST" ] || HOST=$(rd /proc/sys/kernel/hostname)
MODEL=$(rd /tmp/sysinfo/model 2>/dev/null)
[ -n "$MODEL" ] || MODEL=$(rd /proc/device-tree/model 2>/dev/null | tr -d '\0')
FW=$(sed -n "s/^DISTRIB_DESCRIPTION='\(.*\)'$/\1/p" /etc/openwrt_release 2>/dev/null)
[ -n "$FW" ] || FW=$(uname -sr)

# /proc/stat first line: cpu user nice system idle iowait irq softirq steal ...
# busy = everything except idle+iowait; the page deltas this against the last poll
read -r _cpu _u _n _s _i _w _irq _sirq _st _rest < /proc/stat
CPU_TOTAL=$(( _u + _n + _s + _i + _w + _irq + _sirq + _st ))
CPU_IDLE=$(( _i + _w ))
CPUN=$(grep -c '^processor' /proc/cpuinfo)
# one freq pair per policy (big.LITTLE shows two; the page averages or shows both)
FREQS=
for p in /sys/devices/system/cpu/cpufreq/policy*/scaling_cur_freq; do
    [ -r "$p" ] || continue
    d=$(dirname "$p")
    FREQS="$FREQS{\"cur\":$(n_or_null "$(rd "$p")"),\"max\":$(n_or_null "$(rd "$d/cpuinfo_max_freq")")},"
done
FREQS=${FREQS%,}

MEM_T=$(awk '/^MemTotal/{print $2}' /proc/meminfo)
MEM_A=$(awk '/^MemAvailable/{print $2}' /proc/meminfo)

# df on / (the ext4 mu300root loop device)
DF=$(df -k / 2>/dev/null | awk 'NR==2{print $2, $3, $4}')
set -- $DF; DISK_T=$1; DISK_U=$2; DISK_A=$3

T_SOC=$(temp_of soc-thmzone)
T_CPU=$(temp_of apcpu0-thmzone)
T_NR=$(temp_of nr0-thmzone)
T_BRD=$(temp_of board-thmzone)
T_HOT=$(temp_hottest)

# ------------------------------------------------------------------- power
# Only the U30 Air has a battery (the F50 and the V50 have none). Its fuel gauge is "battery" under 5.4 (the
# vendor charger manager) and "sc27xx-fgu" under mainline (UMP9620, FINDINGS
# 33d); any other supply of type Battery is taken after those. The F50 has
# none, but the same PMIC: under mainline its fuel gauge appears with made-up
# values, so an F50 reports no battery and the page hides the tile.
# voltage_now is microvolts, current_now microamps: positive into the battery
# under mainline (the status comes from bq256xx-charger, patch 0010; without
# it patch 0006 derives "Charging" from current > 20 mA); the page goes by
# status first, the sign only for Unknown and the like. An install
# whose ramdisk does not name the device reads as an F50 under mainline (no
# charger_policy_service in that device tree): no tile, never a wrong one. The
# charger (5.4: "usb"/"ac") says whether external power is on and, where it
# exposes them, the input voltage and current; mainline: bq256xx-charger (online only).
PSY=${MU300_POWER_SUPPLY_DIR:-/sys/class/power_supply}
P_DIR=
case $(mu300-device 2>/dev/null) in f50|v50) ;; *)
    for d in "$PSY/battery" "$PSY/sc27xx-fgu" "$PSY"/*; do
        [ -d "$d" ] || continue
        [ "$(rd "$d/present")" = 0 ] && continue
        case ${d##*/} in
            battery|sc27xx-fgu) [ -r "$d/capacity" ] || [ "$(rd "$d/type")" = Battery ] || continue ;;
            *) [ "$(rd "$d/type")" = Battery ] || continue ;;
        esac
        P_DIR=$d; break
    done
    ;; esac
P_PRESENT=0 P_CAP= P_STATUS= P_V= P_I= P_USB= P_IN_V= P_IN_I=
if [ -n "$P_DIR" ]; then
    P_PRESENT=1
    P_CAP=$(rd "$P_DIR/capacity")
    P_STATUS=$(rd "$P_DIR/status")
    P_V=$(rd "$P_DIR/voltage_now")
    P_I=$(rd "$P_DIR/current_now")
    # the first USB/Mains supply that is online, else whether any says 0
    for d in "$PSY"/*; do
        case $(rd "$d/type") in USB*|Mains) ;; *) continue ;; esac
        o=$(rd "$d/online")
        case $o in 1) ;; 0) P_USB=0; continue ;; *) continue ;; esac
        P_USB=1
        P_IN_V=$(rd "$d/voltage_now")
        P_IN_I=$(rd "$d/current_now")
        [ -n "$P_IN_I" ] || P_IN_I=$(rd "$d/input_current_now")
        break
    done
fi
case "$P_CAP" in ''|*[!0-9]*) P_CAP= ;; esac
# volts with two decimals, microamps as an integer, watts = |V x I| with two
power_v() { awk -v v="$1" 'BEGIN{if(v ~ /^-?[0-9]+$/ && v+0>0)printf "%.2f",v/1000000}'; }
power_i() { awk -v v="$1" 'BEGIN{if(v ~ /^-?[0-9]+$/)printf "%d",v}'; }
power_w() { awk -v v="$1" -v i="$2" 'BEGIN{if(v ~ /^-?[0-9]+$/ && i ~ /^-?[0-9]+$/ && v+0>0){w=v*i/1e12; if(w<0)w=-w; printf "%.2f",w}}'; }
P_W=$(power_w "$P_V" "$P_I")
P_IN_W=$(power_w "$P_IN_V" "$P_IN_I")
P_V=$(power_v "$P_V"); P_I=$(power_i "$P_I")
P_IN_V=$(power_v "$P_IN_V"); P_IN_I=$(power_i "$P_IN_I")

# ------------------------------------------------------- interface counters
net_obj() {  # net_obj IFACE -> {"rx":N,"tx":N,"up":0|1} or null
    # an interface name by safe_iface's rule, or nothing is read: the name becomes a /sys path
    [ -n "$1" ] && [ "$(safe_iface "$1" '')" = "$1" ] || { echo null; return; }
    local d=/sys/class/net/$1
    [ -d "$d" ] || { echo null; return; }
    local rx tx up
    rx=$(rd "$d/statistics/rx_bytes"); tx=$(rd "$d/statistics/tx_bytes")
    case "$(rd "$d/operstate")" in up) up=1 ;; *) up=0 ;; esac
    printf '{"rx":%s,"tx":%s,"up":%d}' "$(n_or_null "$rx")" "$(n_or_null "$tx")" "$up"
}

# ------------------------------------------------------------------- Wi-Fi
# configuration truth is uci (the driver reports nothing useful); per-client detail
# comes from the driver's station table, names and addresses from the DHCP leases.
# ONE "uci show wireless" instead of nine "uci get": each uci call costs a fork
# plus config parse and they added up to most of this script's runtime.
WSHOW=$(t3 uci -q show wireless 2>/dev/null)
wu() {  # wu KEY -> value ('' when absent); KEY like "radio0.channel"
    printf '%s\n' "$WSHOW" | sed -n "s/^wireless\\.$1='\\(.*\\)'$/\\1/p" | head -n1
}
# anonymous sections appear in "uci show" under their cfg id, and named ones use
# their name - either way the section type line has no quotes; resolve the first
# wifi-iface section once and read its options through that key
IFKEY=$(printf '%s\n' "$WSHOW" | sed -n "s/^wireless\\.\\([^.]*\\)=wifi-iface\$/\\1/p" | head -n1)
W_SSID=$(wu "${IFKEY:-x}.ssid")
W_CH=$(wu 'radio0.channel')
W_BAND=$(wu 'radio0.band')
[ -n "$W_BAND" ] || W_BAND=$(wu 'radio0.hwmode')
W_HT=$(wu 'radio0.htmode')   # HE80 / VHT40 / HT20 -> the number is the width
W_WIDTH=$(printf '%s' "$W_HT" | tr -cd '0-9' | head -c 2)
[ -n "$W_WIDTH" ] && W_WIDTH="$W_WIDTH MHz"
W_COUNTRY=$(wu 'radio0.country')
W_ENC=$(wu "${IFKEY:-x}.encryption")
[ -n "$W_ENC" ] || W_ENC=none
W_HIDDEN=$(wu "${IFKEY:-x}.hidden")
W_HOSTAPD=0
HAPD=$(t3 ubus call "hostapd.$WIFI_DEVICE" get_status 2>/dev/null)
printf '%s' "$HAPD" | grep -q '"status": *"ENABLED"' && W_HOSTAPD=1
W_DIS=$(wu 'radio0.disabled')
[ "$W_DIS" = "1" ] && W_UP=0 || W_UP=1
[ -d "/sys/class/net/$WIFI_DEVICE" ] || W_UP=0
[ "$W_HOSTAPD" = 1 ] || W_UP=0
# station table: one block per client - mac, signal, tx/rx bitrate, connected time. A row is written when its block
# ends (the signal line comes before the bitrates and the connected time), and a client the SC2355 driver reports
# without metrics still counts. dnsmasq's leases file holds the MAC in lower case and "*" for a client that sent no
# name. Based on kanoqwq/mu300-linux@373e191.
LEASES_FILE=${MU300_DHCP_LEASES:-/tmp/dhcp.leases}
station_rows() {
    awk '
    function emit(   a, n, i) {
        n = split(mac, a, ":")
        if (n != 6) return
        for (i = 1; i <= n; i++)
            if (a[i] !~ /^[0-9a-f][0-9a-f]$/) return
        if (seen[mac]++) return
        printf "%s|%s|%s|%s|%s\n", mac, sig, tx, rx, ct
    }
    /^Station[ \t]+/ { emit(); mac = tolower($2); sig = tx = rx = ct = ""; next }
    /^[ \t]+signal:/ && $2 ~ /^-?[0-9]+([.][0-9]+)?$/ && $2 + 0 != 0 { sig = $2 + 0 }
    /^[ \t]+tx bitrate:/ && $3 ~ /^[0-9]+([.][0-9]+)?$/ { tx = $3 " Mbit/s" }
    /^[ \t]+rx bitrate:/ && $3 ~ /^[0-9]+([.][0-9]+)?$/ { rx = $3 " Mbit/s" }
    /^[ \t]+connected time:/ && $3 ~ /^[0-9]+$/ { ct = sprintf("%d min", int($3 / 60)) }
    END { emit() }'
}
W_CLIENTS=$(t3 iw dev "$WIFI_DEVICE" station dump 2>/dev/null | station_rows)
# SC2355's "station dump" lists only each MAC (and the time); "station get MAC" has the metrics (measured on the U30
# Air: "rx bitrate: 144.4 MBit/s", "signal: 0 dBm", "tx bitrate: (unknown)"). So a row without them asks once per
# listed client, at most 16, 2 s each; a field that stays unknown (signal 0, "(unknown)", no connected time) is null.
# The MAC was checked to be six hex pairs by station_rows, so it reaches iw as one plain argument.
station_fill() {
    local mac sig tx rx ct g asked=0
    while IFS='|' read -r mac sig tx rx ct; do
        [ -n "$mac" ] || continue
        if { [ -z "$sig" ] || [ -z "$tx" ] || [ -z "$rx" ] || [ -z "$ct" ]; } && [ "$asked" -lt 16 ]; then
            asked=$((asked + 1))
            g=$(t2 iw dev "$WIFI_DEVICE" station get "$mac" 2>/dev/null | station_rows | head -n 1)
            if [ "${g%%|*}" = "$mac" ]; then
                set -f; local IFS='|'; set -- $g; IFS=' 	
'; set +f
                sig=${sig:-${2:-}}; tx=${tx:-${3:-}}; rx=${rx:-${4:-}}; ct=${ct:-${5:-}}
            fi
        fi
        printf '%s|%s|%s|%s|%s\n' "$mac" "$sig" "$tx" "$rx" "$ct"
    done
}
W_CLIENTS=$(printf '%s\n' "$W_CLIENTS" | station_fill)
W_CN=0; W_CLIST=
while IFS='|' read -r mac sig txr rxr ct; do
    [ -n "$mac" ] || continue
    line=$(awk -v m="$mac" 'tolower($2) == m { print $3 "|" $4; exit }' "$LEASES_FILE" 2>/dev/null)
    ip=${line%%|*}; host=${line#*|}
    { [ "$host" = "$line" ] || [ "$host" = '*' ]; } && host=
    W_CLIST="$W_CLIST{\"mac\":$(qs "$mac"),\"host\":$(qs "$host"),\"ip\":$(qs "$ip"),\"signal\":$(n_or_null "$sig"),\"tx\":$(qs "$txr"),\"rx\":$(qs "$rxr"),\"conn\":$(qs "$ct")},"
    W_CN=$((W_CN + 1))
done <<EOF2
$(printf '%s\n' "$W_CLIENTS")
EOF2
W_CLIST=${W_CLIST%,}
LAN_LEASES=$(cat "$LEASES_FILE" 2>/dev/null | wc -l)
# recent DHCP leases (host/ip/mac + remaining time) - shows devices that were
# here even when nobody is associated right now
NOWS=$NOW
LEASES=
while read -r exp mac ip host _cid; do
    [ -n "$mac" ] || continue
    [ "$host" = "*" ] && host=
    case $exp in ''|*[!0-9]*) exp=$NOWS ;; esac   # never a file value in $(( ))
    left=$(( exp - NOWS ))
    [ "$left" -lt 0 ] && left=0
    LEASES="$LEASES{\"host\":$(qs "$host"),\"ip\":$(qs "$ip"),\"mac\":$(qs "$mac"),\"left\":$left},"
done < "$LEASES_FILE" 2>/dev/null
LEASES=${LEASES%,}
LAN_IP=$(t2 ip -4 addr show "$LAN_DEVICE" 2>/dev/null | awk '/inet /{split($2,a,"/"); print a[1]; exit}')

# ---------------------------------------------------------------- modem/path
# the same liveness rule mu300-atd uses: the URC log on nr0 is written to as
# long as the modem is running, whatever it thinks of our commands
URCLOG=/run/mu300-at/urc/stty_nr$((SIM_SLOT * 3)).log
if [ -f "$URCLOG" ]; then
    AGE=$(( NOW - $(date -r "$URCLOG" +%s 2>/dev/null || echo 0) ))
    [ "$AGE" -lt 240 ] && MODEM_ALIVE=1 || MODEM_ALIVE=0
else
    MODEM_ALIVE=0
fi
ATD_OK=0; /usr/libexec/unisoc-modem/at --available >/dev/null 2>&1 && ATD_OK=1
[ "$MODEM_ALIVE" = 1 ] || MODEM_ALIVE=$ATD_OK
DATA_PAUSED=0; [ -e /run/mu300-mobile-data-down ] && DATA_PAUSED=1
# What the card in use said of itself at its last check (mu300-sim-state, FINDINGS 186: AT+CPIN? when the dial began
# and after each SIM event): absent, ready or locked, null when it has not been asked this boot. A file in /run, no
# AT command. The home page says "No SIM card" by it instead of "Radio off" (kanoqwq's fe52afe3: with no card the
# radio is off as well, and the page used to name the radio instead of the missing card).
SIM_STATE=$(head -c 16 "${MU300_SIM_STATE_DIR:-/run/mu300}/sim$SIM_SLOT.state" 2>/dev/null | tr -cd 'a-z')
case $SIM_STATE in absent|ready|locked) SIM_STATE="\"$SIM_STATE\"" ;; *) SIM_STATE=null ;; esac
# Tracked connections: the kernel's counter needs no CONFIG_NF_CONNTRACK_PROCFS (the mainline kernel has no
# /proc/net/nf_conntrack); the table is the fallback; neither readable is unknown (null), never a made-up 0. The
# counter is read with cat in one go: a sysctl file may answer a second short read with EOF. Based on
# kanoqwq/mu300-linux@373e191.
conntrack_count() {
    local count counter=${MU300_CONNTRACK_COUNT:-/proc/sys/net/netfilter/nf_conntrack_count}
    local table=${MU300_CONNTRACK_TABLE:-/proc/net/nf_conntrack}
    if [ -r "$counter" ] && count=$(cat "$counter" 2>/dev/null); then
        case $count in ''|*[!0-9]*) ;; *) echo "$count"; return ;; esac
    fi
    if [ -r "$table" ] && count=$(wc -l < "$table" 2>/dev/null); then
        echo $((count + 0)); return
    fi
    echo null
}
CONNS=$(conntrack_count)

# --------------------------------------------------------------------- VPN
VPN_ENABLED=0; VPN_ENGINE=""; VPN_UP=0
# ENABLE is still vpn.conf's. The engine is the active profile's TYPE (/etc/mu300/vpn/active names the profile,
# its meta holds TYPE='...'); a device that has not been migrated yet, or runs an older mu300-vpn, has only
# vpn.conf's ENGINE. The id is checked before it becomes a path and meta is read with sed, never sourced.
if [ -r /etc/mu300/vpn.conf ]; then
    grep -q '^ENABLE=1' /etc/mu300/vpn.conf && VPN_ENABLED=1
fi
VPN_ACTIVE=$(head -c 64 /etc/mu300/vpn/active 2>/dev/null | head -n1)
case $VPN_ACTIVE in
    *[!a-z0-9-]*|'') ;;
    *) [ ${#VPN_ACTIVE} -le 32 ] && VPN_ENGINE=$(sed -n "s/^TYPE=//p" "/etc/mu300/vpn/profiles/$VPN_ACTIVE/meta" 2>/dev/null \
                                                     | tail -n1 | sed "s/^'//; s/'\$//") ;;
esac
[ -n "$VPN_ENGINE" ] || VPN_ENGINE=$(sed -n 's/^ENGINE=//p' /etc/mu300/vpn.conf 2>/dev/null | tail -n1)
# up: the interface the last run brought up (/run/mu300-vpn/iface, any driver), or the two legacy engines' own
# names; a name is only given to ip when it looks like one
VPN_IF=$(head -c 32 /run/mu300-vpn/iface 2>/dev/null | head -n1)
case $VPN_IF in *[!A-Za-z0-9_.-]*|'') VPN_IF="" ;; esac
if { [ -n "$VPN_IF" ] && ip link show "$VPN_IF" >/dev/null 2>&1; } \
    || ip link show xtun >/dev/null 2>&1 || ip link show sbtun >/dev/null 2>&1; then VPN_UP=1; fi
# the VPN is a module of its own (github.com/dikeckaan/mu300-linux-vpn): present when its hook linked mu300-vpn and the
# service into this system (the images have neither)
CAP_VPN=0; [ -x /opt/mu300/bin/mu300-vpn ] && [ -x /etc/init.d/mu300-vpn ] && CAP_VPN=1
# orphaned: the VPN on with its kill switch and no module to enforce it - mobile data and the Wi-Fi client then stay
# down (lib/vpn-orphan.sh; MU300_SYSROOT, MU300_VPN_CMD, MU300_VPN_ORPHAN_LIB: tests)
VPN_ORPHANED=0
_vol=${MU300_VPN_ORPHAN_LIB:-/opt/mu300/lib/vpn-orphan.sh}
if [ -r "$_vol" ] && . "$_vol" && vpn_killswitch_orphaned "${MU300_VPN_CMD:-/opt/mu300/bin/mu300-vpn}" "${MU300_SYSROOT:-}"; then
    VPN_ORPHANED=1
fi
CAP_DUALBOOT=0; [ -x /opt/mu300/bin/mu300-next-boot ] && CAP_DUALBOOT=1
# mu300-next-boot lock: the wish on the Linux disk (the panel shows it; the slot itself is in misc)
BOOT_LOCK=0
for _d in /mnt/mu300-disk ""; do [ -f "$_d/.mu300/boot-lock" ] && { BOOT_LOCK=1; break; }; done

# A newer release: the note mu300-update keeps (notice, at boot and every 6 hours; this only reads it). Its tag, for
# the home page's link to System > Update.
UPDATE_TAG=$(sed -n 's/^mu300-linux \(v[0-9.]*\) is out .*/\1/p' "${MU300_NOTICE:-/run/mu300/update-available}" 2>/dev/null | head -n1)
# (a release tag, docs/FINDINGS.md 125: vYYYY.MM.DD, and vYYYY.MM.DD.N after v2026.10.27)
printf '%s\n' "$UPDATE_TAG" | LC_ALL=C grep -Eqx -- 'v[0-9]{4}\.[0-9]{2}\.[0-9]{2}|v[0-9]{4}\.(0[1-9]|1[0-2])\.(0[1-9]|[12][0-9]|3[01])\.[1-9][0-9]?' || UPDATE_TAG=

# ------------------------------------------------------------- data usage
# mu300-traffic's service writes this summary after each of its readings (RAM, once a minute): today and the
# billing cycle, against the cap. Numbers and fixed words only; anything else is left out.
TSUM=${MU300_TRAFFIC_SUMMARY:-/run/mu300/traffic/summary}
tsum() { sed -n "s/^$1=//p" "$TSUM" 2>/dev/null | head -n1; }
tint() { v=$(tsum "$1"); case $v in ''|*[!0-9]*|0?*) echo 0 ;; *) echo "$v" ;; esac; }
T_LEVEL=$(tsum level); case $T_LEVEL in ok|warn|over|none) ;; *) T_LEVEL= ;; esac

# ------------------------------------------------------------------ USB link
# The USB-C port's link speed as negotiated with whatever sits at the other end of the cable. Device
# mode: the gadget's UDC reports it ("high-speed", "super-speed", "super-speed-plus"). Host mode (mu300-usb host) has
# no UDC, and the attached device's own speed file is the answer. A USB 2.0 only cable or host port caps a 10 Gbps
# capable port at 480 Mbps, which is why the page shows this as a downgrade instead of hiding it.
USB_UDC_DIR=${MU300_UDC_DIR:-/sys/class/udc}
USB_DEV_DIR=${MU300_USB_DEVICES_DIR:-/sys/bus/usb/devices}
usb_mbps() {  # a speed word from sysfs, or a number already in Mbps -> integer Mbps (empty when unknown)
    case $1 in
        low-speed) echo 1 ;;
        full-speed) echo 12 ;;
        high-speed) echo 480 ;;
        super-speed) echo 5000 ;;
        super-speed-plus) echo 10000 ;;
        ''|*[!0-9]*) ;;
        *) echo "$1" ;;
    esac
}
usb_link() {  # -> {"role":"device","speed":"high-speed","mbps":480,"max":"super-speed-plus","max_mbps":10000} | null
    local u s m best best_s
    for u in "$USB_UDC_DIR"/*; do
        [ -r "$u/current_speed" ] || continue
        s=$(rd "$u/current_speed"); m=$(rd "$u/maximum_speed")
        printf '{"role":"device","speed":%s,"mbps":%s,"max":%s,"max_mbps":%s}' \
            "$(qs "$s")" "$(n_or_null "$(usb_mbps "$s")")" "$(qs "$m")" "$(n_or_null "$(usb_mbps "$m")")"
        return
    done
    # host mode: the fastest attached device; a root hub (1d6b) reports the port's own speed, not a device's
    for u in "$USB_DEV_DIR"/*/speed; do
        [ -r "$u" ] || continue
        [ "$(rd "${u%/speed}/idVendor")" = 1d6b ] && continue
        s=$(rd "$u"); m=$(usb_mbps "$s"); [ -n "$m" ] || continue
        if [ -z "$best" ] || [ "$m" -gt "$best" ] 2>/dev/null; then best=$m; best_s=$s; fi
    done
    [ -n "$best" ] || { echo null; return; }
    printf '{"role":"host","speed":%s,"mbps":%s,"max":null,"max_mbps":null}' "$(qs "$best_s")" "$best"
}

# ------------------------------------------------------------------ output
printf '{"ts":%d,"uptime":%d,"host":%s,"model":%s,"fw":%s,"kernel":%s,' \
    "$NOW" "$UPTIME" "$(qs "$HOST")" "$(qs "$MODEL")" "$(qs "$FW")" "$(qs "$(uname -r)")"
printf '"cpu":{"n":%d,"total":%d,"idle":%d,"freqs":[%s]},' "$CPUN" "$CPU_TOTAL" "$CPU_IDLE" "${FREQS:-}"
printf '"mem":{"total_kb":%s,"avail_kb":%s},' "$(n_or_null "$MEM_T")" "$(n_or_null "$MEM_A")"
printf '"storage":{"total_kb":%s,"used_kb":%s,"avail_kb":%s},' "$(n_or_null "$DISK_T")" "$(n_or_null "$DISK_U")" "$(n_or_null "$DISK_A")"
printf '"temps":{"soc":%s,"cpu":%s,"modem":%s,"board":%s,"hottest":%s},' \
    "$(f_or_null "$T_SOC")" "$(f_or_null "$T_CPU")" "$(f_or_null "$T_NR")" "$(f_or_null "$T_BRD")" "$(f_or_null "$T_HOT")"
printf '"power":{"present":%d,"capacity":%s,"status":%s,"volt":%s,"ua":%s,"w":%s,"usb":%s,"in_volt":%s,"in_ua":%s,"in_w":%s},' \
    "$P_PRESENT" "$(n_or_null "$P_CAP")" "$(qs "$P_STATUS")" "$(n_or_null "$P_V")" "$(n_or_null "$P_I")" \
    "$(n_or_null "$P_W")" "$(n_or_null "$P_USB")" "$(n_or_null "$P_IN_V")" "$(n_or_null "$P_IN_I")" "$(n_or_null "$P_IN_W")"
printf '"net":{"mobile":%s,"sipa_eth0":%s,"brlan":%s,"wlan0":%s,"usb0":%s},' \
    "$(net_obj "$DATA_DEVICE")" "$(net_obj "$DATA_DEVICE")" "$(net_obj "$LAN_DEVICE")" "$(net_obj "$WIFI_DEVICE")" "$(net_obj "$USB_DEVICE")"
printf '"usblink":%s,' "$(usb_link)"
# the interface the page reads its live rates of (from /proc/net/dev, every second)
printf '"data_device":%s,' "$(qs "$DATA_DEVICE")"
printf '"sim":%s,' "$SIM_JSON"
if [ -n "$T_LEVEL" ]; then
    printf '"traffic":{"level":"%s","today":%s,"used":%s,"cap":%s,"warn":%s,"clock":%s},' "$T_LEVEL" \
        "$(( $(tint today_rx) + $(tint today_tx) ))" "$(tint used)" "$(tint cap)" "$(tint warn)" "$(tint clock)"
else
    printf '"traffic":null,'
fi
printf '"wan":{"up":%d,"uptime":%s,"proto":%s,"apn":%s,"ip4":%s,"ip6":%s,"dns":%s,"roaming":{"allowed":%d,"held":%d}},' \
    "$wan_up" "$(n_or_null "$wan_uptime")" "$(qs "$wan_proto")" "$(qs "$apn")" "$(qs "$wan_ip4")" "$(qs "$wan6_ip")" "$(qs "$wan_dns")" \
    "$roam_allowed" "$roam_held"
printf '"wifi":{"up":%d,"ssid":%s,"channel":%s,"band":%s,"width":%s,"country":%s,"enc":%s,"hidden":%s,"hostapd":%d,"clients":[%s],"clients_n":%d},' \
    "$W_UP" "$(qs "$W_SSID")" "$(qs "$W_CH")" "$(qs "$W_BAND")" "$(qs "$W_WIDTH")" "$(qs "$W_COUNTRY")" "$(qs "$W_ENC")" "$(n_or_null "$W_HIDDEN")" "$W_HOSTAPD" "${W_CLIST:-}" "$W_CN"
printf '"lan":{"leases":%s,"ip":%s,"list":[%s]},' "$(n_or_null "$LAN_LEASES")" "$(qs "$LAN_IP")" "${LEASES:-}"
printf '"modem":{"alive":%d,"atd":%d,"data_paused":%d,"sim_state":%s},' "$MODEM_ALIVE" "$ATD_OK" "$DATA_PAUSED" "$SIM_STATE"
printf '"capabilities":{"vpn":%d,"dualboot":%d,"bootlock":%d},' "$CAP_VPN" "$CAP_DUALBOOT" "$BOOT_LOCK"
printf '"update":%s,' "$(qs "$UPDATE_TAG")"
printf '"conns":%s,' "$(n_or_null "$CONNS")"
printf '"vpn":{"enabled":%d,"engine":%s,"up":%d,"orphaned":%d}}\n' "$VPN_ENABLED" "$(qs "$VPN_ENGINE")" "$VPN_UP" "$VPN_ORPHANED"
