#!/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 $SCRIPT/utils/wifi.sh
source $SCRIPT/utils/wifi-extend.sh
source $SCRIPT/utils/hotspot.sh
source $SCRIPT/utils/date.sh
source /usr/share/libubox/jshn.sh

now=`nowAsUnixEpoch`

nextSession() {
  [ -z "$json" ] && echo -n "session "
  echo -n "$(json_dump)"
  [ -z "$json" ] || echo -n ", "
  json_cleanup

  [ -f kickedOut ] && $(cd /tmp; rm -rf "$sessionDir/$mac")
  continue
}

logoutMac() {
  echo  "  logout reason $3" 1>&2
  ssid="$1" mac="$2" force=self $SCRIPT/session/logout.sh
  json_add_string stoppedAt "${now}000"
  json_add_string stopReason "$3"
  echo -n "$3" > kickedOut
  nextSession
}

updateSessionOfSsid() {
  local ssid="$1"
  local index="$2"
  echo "ssid $ssid" 1>&2

  local ssidName=`getSsidName $index $ssid 1`

  local sessionDir="/var/stats/ssid${ssid}/sessions"
  [ -d "$sessionDir" ] && local macs=`ls -1 "$sessionDir"`;

  for mac in $macs ; do
    cd "$sessionDir/$mac" && echo "session $mac" 1>&2 || continue
    json_init
    json_add_string ssid $ssid
    json_add_string ssidName "$ssidName"
    [ -s mode ] && json_add_string mode "$(cat mode)"
    json_add_string mac $mac

    if [ -f sessionId ] ; then
      local sessionId=`cat sessionId`
      json_add_string id "$sessionId"
    fi

    local ip=`cat ip 2>/dev/null`
    if [ -z "$ip" ] && [ -f "/var/stats/arp/$mac" ]; then
      ip=`cat /var/stats/arp/$mac`
      echo -n $ip > ip
    fi
    if [ ! -z "$ip" ] ; then
      echo "  ip $ip" 1>&2
      json_add_string ip $ip
    fi

    local download=0
    local upload=0
    [ -s txBytes ] && download=`cat txBytes 2>/dev/null`
    [ -s rxBytes ] && upload=`cat rxBytes 2>/dev/null`
    echo "  data $download/$upload" 1>&2
    local totalData=$((download + upload))
    json_add_double totalDownload $download
    json_add_double totalUpload $upload

    local connTime=0
    local sessTime=0
    if [ -f connectedAt ] ; then
      local connectedAt=`cat connectedAt`
      connTime=$((now - connectedAt))
      echo "  connect time $connTime" 1>&2
      json_add_string connectedAt "${connectedAt}000"
    fi
    if [ -f disconnectedAt ] ; then
      echo  "  disconnected" 1>&2
      local disconnectedAt=`cat disconnectedAt`
      json_add_string disconnectedAt "${disconnectedAt}000"
    fi

    if [ -f startedAt ] ; then
      local startedAt=`cat startedAt`
      sessTime=$((now - startedAt))
      echo "  session time $sessTime" 1>&2
      json_add_string startedAt "${startedAt}000"
    fi

    if [ -f ua ] ; then
      json_add_string ua "$(cat ua)"
    fi

    if [ -s kickedOut ] ; then
      logoutMac $ssid $mac "`cat kickedOut`"
    fi

    # idle
    if [ -s idleTimeout ] ; then
      idleTimeout=`cat idleTimeout`
    else
      [ -s authenticated ] && idleTimeout=900 || idleTimeout=300
    fi

    local updatedAt=`cat updatedAt`
    local idle=$((now - updatedAt))
    [ -f disconnectedAt ] && local disconnectedAt=`cat disconnectedAt` && idle=$((now - disconnectedAt))
    if [ "$idle" -ge "$idleTimeout" ] ; then
      logoutMac $ssid $mac "IdleTimeout"
    else
      json_add_string lastActiveAt "$((now - idle))000"
    fi

    # check limitation
    if [ -s expireDate ] && [ "`cat expireDate`" -lt "$now" ] ; then
      logoutMac $ssid $mac "Expired"
    fi
    if [ -s dataRemaining ] && [ "`cat dataRemaining`" -lt "$totalData" ] ; then
      logoutMac $ssid $mac "DataExpired"
    fi
    if [ -s timeRemaining ] && [ "`cat timeRemaining`" -lt "$sessTime" ] ; then
      logoutMac $ssid $mac "TimeExpired"
    fi
    if [ -s sessionTimeout ] && [ "`cat sessionTimeout`" -lt "$sessTime" ] ; then
      logoutMac $ssid $mac "SessionTimeout"
    fi

    if [ -s authenticated ] ; then
      json_add_boolean authenticated 1
      resetTimeoutOfIpInIpset $ssid $mac $((idleTimeout + 60))
    else
      json_add_boolean authenticated 0
    fi

    nextSession
  done
}

updateSession() {
  [ -z "$json" ] || echo -n "["
  local ssids=`getEnabledSsidList`
  local index=0
  for ssid in $ssids ; do
    index=$((index + 1))
    updateSessionOfSsid $ssid $index
  done
  [ -z "$json" ] || echo "null]"
}

updateSession

exit 0