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

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

source $SCRIPT/utils/wifi.sh

mkdir -p /etc/persistent/

oldHash=`md5sum /etc/persistent/*.maclist | md5sum`

ssids=`getEnabledSsidList`
for ssid in $ssids ; do
  echo > "/etc/persistent/ssid${ssid}.maclist"

  eval macFilter="\$SSID${ssid}_MAC_FILTER_ENABLED"
  if [ "$macFilter" == 1 ] ; then
    eval macs="\$SSID${ssid}_MAC_FILTER_MACS"
    echo $macs | tr ";" "\n" > "/etc/persistent/ssid${ssid}.maclist"
    eval policy="\$SSID${ssid}_MAC_FILTER_POLICY"
  fi

  [ "$policy" == allow ] || policy=deny
  if [ "$policy" == deny ] ; then
    echo "$BLOCKED_MACS" | tr ";" "\n" >> "/etc/persistent/ssid${ssid}.maclist"
    [ -f /tmp/blocked.maclist ] && cat /tmp/blocked.maclist >> "/etc/persistent/ssid${ssid}.maclist"
  fi

  macs=`cat "/etc/persistent/ssid${ssid}.maclist" | grep : | uniq`
  echo $macs > "/etc/persistent/ssid${ssid}.maclist"

  if [ "`which hostapd_cli`" ] ; then
    infs=`getSsidWirelessInf $ssid`
    for inf in $infs ; do
      hostapd_cli -i $inf accept_acl CLEAR 2>/dev/null
      hostapd_cli -i $inf deny_acl CLEAR 2>/dev/null

      [ "$policy" == allow ] && acl=accept_acl || acl=deny_acl
      for mac in $macs ; do
        hostapd_cli -i $inf $acl ADD_MAC $mac
      done
    done
  fi
done

newHash=`md5sum /etc/persistent/*.maclist | md5sum`

[ -z "`which hostapd_cli`" ] && [ "$oldHash" != "$newHash" ] && wifi