#!/bin/sh

# session=
#   error: false,
#   limitations:
#     dataRemaining: 1073742848
#     expireDate: 2017-12-07T06:46:08.502Z
#     maxDevice: 1
#     maxDownload: 4194304
#     maxUpload: 4194304
#     sessionTimeout: 600
#     timeRemaining: 3600
#   session:
#     id: AV-_FHn1WvquMTUFKyTy
#     ip: 10.14.1.248
#     lastActiveAt: 2017-11-15T09:48:30.999Z
#     mac: 0C:30:21:62:F0:8C
#     ssid: 1
#     startedAt: 2017-11-15T09:48:30.999Z
#     totalDownload: 0
#     totalTime: 0
#     totalUpload: 0
#     updatedAt: 2017-11-15T09:48:30.999Z

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

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

source $SCRIPT/utils/date.sh
source $SCRIPT/utils/random.sh
source $SCRIPT/utils/wifi.sh
source $SCRIPT/utils/hotspot.sh
source $SCRIPT/utils/network.sh
source $SCRIPT/utils/qos.sh

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

sessionDir="$baseDir/ssid${ssid}/sessions/$mac"
mkdir -p "$sessionDir" && cd "$sessionDir"

if [ -z "$id" ] ; then
  id=`echo "$mac" | tr '[A-Z]' '[a-z]' | sed s/://g`
  id="${id}-`nowAsUnixEpoch`"
fi
echo -n "$id" > sessionId

# Allow user
addIpToIpset $ssid $mac
if which conntrack ; then
  conntrack -D -s $ip
  conntrack -D -d $ip
fi

echo -n "$ip" > ip
echo -n `isoToUnixEpoch "$startedAt"` > startedAt
echo -n `isoToUnixEpoch "$startedAt"` > updatedAt
[ ! -z "$idleTimeout" ] && echo -n "$idleTimeout" > idleTimeout
[ ! -z "$expireDate" ] && echo -n `isoToUnixEpoch "$expireDate"` > expireDate
[ ! -z "$sessionTimeout" ] && echo -n "$sessionTimeout" > sessionTimeout
[ ! -z "$dataRemaining" ] && echo -n "$dataRemaining" > dataRemaining
[ ! -z "$timeRemaining" ] &&  -n "$timeRemaining" > timeRemaining
[ ! -z "$maxDownload" ] ; echo -n "$maxDownload" > maxDownload
[ ! -z "$maxUpload" ] ; echo -n "$maxUpload" > maxUpload
echo -n true > authenticated
rm -f _*

# Set QOS
[ -z "$maxDownload" -a -z "$maxUpload" ] || enableQosOfIpOnSsid $ssid $ip "$maxDownload" "$maxUpload"
