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

source $CONFIG/ap.conf
source $CONFIG/ng.conf

source $SCRIPT/utils/date.sh
source $SCRIPT/utils/hotspot.sh

[ -z $ssid -o -z "$mac" ] && exit 0

baseDir="/var/stats"
sessionDir="$baseDir/ssid${ssid}/sessions/${mac}"

# Logout other session with same mac
find $baseDir -type d -name "$mac" | awk -v sDir="$sessionDir" '{
  if ($0 != sDir) system("echo -n User > "$0"/kickedOut")
}'

mkdir -p $sessionDir && cd $sessionDir
now=`nowAsUnixEpoch`

echo -n $mac > mac

[ -f mode ] && oldMode=`cat mode`
[ "$oldMode" != "$mode" ] && switchMode=yes
echo -n $mode > mode

setValue() {
  local name="$1"
  local val="$2"
  eval local oldVal=`cat "_\$name" 2>/dev/null`
  echo -n $val > "_$name"
  [ -z "$switchMode" ] || return
  [ -z "$oldVal" ] && return
  [ $val -lt $oldVal ] && return
  local curVal=`cat $name` 2>/dev/null
  [ -z "$curVal" ] && curVal=0
  local diff=$((val - oldVal))
  echo -n $((curVal + diff)) > "$name"
}

[ -z "$rxBytes" ] || setValue rxBytes "$rxBytes"
[ -z "$rxPackets" ] || setValue rxPackets "$rxPackets"
[ -z "$txBytes" ] || setValue txBytes "$txBytes"
[ -z "$txPackets" ] || setValue txPackets "$txPackets"
[ -z "$txRetries" ] || setValue txRetries "$txRetries"
[ -z "$txFailed" ] || setValue txFailed "$txFailed"

rm -f disconnectedAt 2>/dev/null
if [ ! -f connectedAt ] ; then
  [ -z "$connected" ] && connected=0
  echo -n $((now - connected)) > connectedAt
fi

echo -n $((idle / 1000)) > idle

echo -n $now > updatedAt
