#!/bin/sh

# script to detect new dhcp lease

# this will be called by dnsmasq everytime a new device is connected
# with the following arguments
# $1 = add | old | del
# $2 = mac address
# $3 = ip address
# $4 = device name

[ "$1" == del ] && exit 0

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

# bug on 501
model="`$SCRIPT/model.sh`"
[ $model == 501 ] && exit 0

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

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

debug() {
  [ ! -z "$DEBUG" ] && echo $1 >> /var/log/hotspot.autologin.log
}

hotspots=`getHotspotInstanceList`

mac=$2
ip=$3

for ssid in $hotspots ; do
  infs=`getSsidWirelessInf $ssid`
  for inf in $infs ; do
    iw $i station get $mac &>/dev/null
    [ $? -eq 0 ] && break
  done
  [ -z $inf ] || break
done

[ "$ssid" -eq 0 ] && exit 0

debug "$1 ip $ip ($mac) connected to ssid$ssid ($inf $4)"

eval autoLogin="\$SSID${ssid}_AUTO_LOGIN"
if [ "$autoLogin" != 1 ] ; then
  debug "auto login dsabled"
  exit 0
fi

ipset test "authenticated${ssid}" $mac &>/dev/null
if [ $? -eq 0 ] ; then
  debug "logged in"
  exit 0
fi

ipset -! add "autologin${ssid}" $ip timeout 10
