#!/bin/sh

[ -z "$ROOT" ] && ROOT=/www
CONFIG=$ROOT/config
SCRIPT=$ROOT/script

[ -f $CONFIG/ng.conf ] && source $CONFIG/ng.conf
source $CONFIG/ap.conf
source $CONFIG/api.conf

source $SCRIPT/utils/stat.sh
source $SCRIPT/utils/network.sh
source $SCRIPT/utils/wifi.sh
source $SCRIPT/utils/wifi-extend.sh
source /usr/share/libubox/jshn.sh

json_init

# system
json_add_string uptime "`getUptime`"
json_add_string cpu "`getCpuLoad`"
json_add_string ramFree "`getRamFree`"
json_add_string ramTotal "`getRamTotal`"

# network
json_add_string ip "`getWanIp`"
json_add_string mac "`getWanMac`"
json_add_string gateway "`getGateway`"

json_add_string version "`cat $ROOT/version`"

# stations
ssids=`getEnabledSsidList`
radios=`getRadioCount`
index=0

json_add_array wireless
for ssid in $ssids ; do
  index=$((index + 1))
  for radio in `seq 1 $radios` ; do
    mode=`getRadioMode $radio`
    [ ! -n "$mode" ] && mode=2G

    json_add_object ssid
    json_add_int ssid "$ssid"
    json_add_string mode "$mode"
    json_add_string ssidName "`getSsidName $index $ssid $radio`"
    json_add_string stations "`getStationList $index $ssid $radio`"
    json_close_object
  done
done
json_close_array

json_add_array wan
wanInfs=`ls -1 /var/stats/wan 2>/dev/null`
for inf in $wanInfs ; do
  cd "/var/stats/wan/$inf"
  json_add_object wan
  json_add_string inf "$inf"
  json_add_string state "`cat state`"
  json_add_string speed "`cat speed`"
  json_add_string txBytes "`cat txBytes`"
  json_add_string rxBytes "`cat rxBytes`"
  json_add_string txRate "`cat txRate`"
  json_add_string rxRate "`cat rxRate`"
  json_add_string txPackets "`cat txPackets`"
  json_add_string rxPackets "`cat rxPackets`"
  json_add_string txDropped "`cat txDropped`"
  json_add_string rxDropped "`cat rxDropped`"
  json_close_object
done
json_close_array

json_add_array lan
lanInfs=`ls -1 /var/stats/lan 2>/dev/null`
for inf in $lanInfs ; do
  cd "/var/stats/lan/$inf"
  json_add_object lan
  json_add_string inf "$inf"
  json_add_string state "`cat state`"
  json_add_string speed "`cat speed`"
  json_add_string txBytes "`cat txBytes`"
  json_add_string rxBytes "`cat rxBytes`"
  json_add_string txRate "`cat txRate`"
  json_add_string rxRate "`cat rxRate`"
  json_add_string txPackets "`cat txPackets`"
  json_add_string rxPackets "`cat rxPackets`"
  json_add_string txDropped "`cat txDropped`"
  json_add_string rxDropped "`cat rxDropped`"
  json_close_object
done
json_close_array

echo "stats $(json_dump)" 1>&2
[ -z "$json" ] && echo -n "stats "
echo "$(json_dump)"
json_cleanup