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

source $CONFIG/ap.conf
source $SCRIPT/utils/wifi.sh
source $SCRIPT/utils/date.sh

collect() {
  source $CONFIG/ng.conf

  local now=`nowAsUnixEpoch`
  echo $now > /tmp/now
  sleep 5

  # connected client
  local ssids=`getEnabledSsidList`
  for ssid in $ssids ; do
    echo > /tmp/ssid$ssid.sta
    local infs=`getSsidWirelessInf $ssid`
    for inf in $infs ; do
      radio=`echo ${inf: -1}`
      mode=`getRadioMode $radio`
      [ -z "$mode" ] && mode=2G
      iw $inf station dump | \
        awk -v ssid="$ssid" -v mode="$mode" -f $SCRIPT/collector/sta-dump.awk >> /tmp/ssid$ssid.sta
    done

    # remove duplicate stations based on idle time
    cat /tmp/ssid$ssid.sta | sort -r | uniq -w 21 | sh

    # disconnected
    [ -d "/var/stats/ssid$ssid/sessions" ] || continue
    find "/var/stats/ssid$ssid/sessions" -type f -name "updatedAt" ! -newer /tmp/now | awk -v now="$now" '{
      path=gensub(/updatedAt/, "disconnectedAt", "g", $0);
      system("[ -f "path" ] || echo -n "now" > "path);
    }'
  done

  # wan stats
  if [ -z "$MOBILE_DEV" ] ; then
    local wanParentInf=`echo $WAN_ETH | cut -d "." -f 1`
    local wanInfs=`ls -1 /sys/class/net/ | grep -e $WAN_ETH -e "${wanParentInf}." | grep -v $LAN_ETH`
  else
    local wanInfs=wwan0
  fi
  for inf in $wanInfs ; do
    dir="/var/stats/wan/$inf"
    mkdir -p $dir
    inf="$inf" dir="$dir" sh $SCRIPT/collector/inf-dump.sh
  done
  find "/var/stats/wan" -type f -name "updatedAt" ! -newer /tmp/now | awk '{
    path=gensub(/updatedAt/, "", "g", $0);
    system("[ -d \""path"\" ] && rm -rf \""path"\"");
  }'

  # lan stats
  if [ ! -z "$LAN_ETH" ] ; then
    dir="/var/stats/lan/$LAN_ETH"
    mkdir -p $dir
    inf="$LAN_ETH" dir="$dir" sh $SCRIPT/collector/inf-dump.sh
  fi
  find "/var/stats/lan" -type f -name "updatedAt" ! -newer /tmp/now | awk '{
    path=gensub(/updatedAt/, "", "g", $0);
    system("[ -d \""path"\" ] && rm -rf \""path"\"");
  }'
}

while true ; do
  collect
done