#!/bin/sh
# Forced-command, read-only WAN byte counters. No user-supplied arguments.
trap 'exit 0' TERM INT HUP
boot=$(cat /proc/sys/kernel/random/boot_id) || exit 1
tick=0
devices='{}'
while :; do
    # Refresh DHCP + IPv6-neighbor identities every 30 seconds; read-only.
    if [ "$tick" -eq 0 ]; then
        devices=$(ip -6 neigh show dev br-lan 2>/dev/null | awk '
            FILENAME != "-" {
                if ($4 ~ /^[A-Za-z0-9_.-]+$/ && $3 ~ /^[0-9.]+$/) {
                    names[tolower($2)]=$4; ips[$3]=$4
                }
                next
            }
            $1 ~ /^[0-9a-fA-F:]+$/ {
                for (i=2;i<NF;i++) if ($i=="lladdr" && names[tolower($(i+1))]!="") ips[$1]=names[tolower($(i+1))]
            }
            END { printf "{"; sep=""; count=0; for (ip in ips) {if(count++>=256)break; printf "%s\"%s\":\"%s\"",sep,ip,ips[ip];sep=","} print "}" }
        ' /tmp/dhcp.leases -)
        [ -n "$devices" ] || devices='{}'
    fi
    tick=$(( (tick + 1) % 15 ))
    read -r uptime rest < /proc/uptime || exit 1
    read -r rx < /sys/class/net/wan/statistics/rx_bytes || exit 1
    read -r tx < /sys/class/net/wan/statistics/tx_bytes || exit 1
    printf '{"boot":"%s","time":%s,"rx":%s,"tx":%s,"devices":%s}\n' "$boot" "$uptime" "$rx" "$tx" "$devices"
    sleep 2
done
