#!/bin/sh

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

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

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

ssid="$1"
if [ -z "$ssid" ] || [ "$ssid" -gt "$NO_SSID" ] ; then
  echo "Invalid SSID $ssid" && exit
fi
radioId="$2"
if [ -z "$radioId" ] ; then
  echo "Invalid radio $radioId" && exit
fi

radioName=`getRadioName $radioId`
radioMode=`getRadioMode $radioId`
modeSuffix=`[ ! -z "$radioMode" ] && echo "_${radioMode}"`

echo "Wireless config $modeSuffix SSID $ssid"

uciKey="wireless.ssid${ssid}${modeSuffix}"

uci -q del $uciKey
[ ! `isSsidEnabled "$ssid"` ] && exit

uci set $uciKey=wifi-iface

ifId=`getWirelessInfId $ssid $radioId`
if [ ! -z "$ifId" ] ; then
  uci set $uciKey.id="$ifId"
else
  ifName=`getWirelessInf $ssid $radioId`
  uci set $uciKey.ifname="$ifName"
fi

uci set $uciKey.device="$radioName"
uci set $uciKey.mode=ap

uci set $uciKey.network=wifi"$ssid"
if [ `isSsidInBridgeMode "$ssid"` ] ; then
  eval vlan="\$SSID${ssid}_VLAN"
  if [ -z "$vlan" ] ; then
    uci set $uciKey.network=wan
  else
    uci set $uciKey.network="vlan${vlan}"
  fi
else
  uci set $uciKey.network=wifi"$ssid"
fi

eval maxStation="\$SSID${ssid}_MAX_STATION"
if [ ! -z "$maxStation" ] && [ "$maxStation" -gt 0 ] ; then
  uci set $uciKey.maxassoc="$maxStation"
fi

eval isolate="\$SSID${ssid}_ISOLATE"
[ "$isolate" != 0 ] && uci set $uciKey.ap_isolate=1

eval hidden="\$SSID${ssid}_HIDDEN"
[ "$hidden" != 0 ] && uci set $uciKey.hidden=1

eval ssidName="\$SSID${ssid}_SSID"
uci set $uciKey.ssid="$ssidName"

eval ssidEncryption="\$SSID${ssid}_ENCRYPTION"
if [ "$ssidEncryption" == wpa ] ; then
  uci set $uciKey.encryption="wpa2"

  eval radiusServer="\$SSID${ssid}_RADIUS_SERVER"
  [ -z "$radiusServer" ] || uci set $uciKey.server="$radiusServer"

  eval radiusPort="\$SSID${ssid}_RADIUS_PORT"
  [ -z "$radiusPort" ] || uci set $uciKey.port="$radiusPort"

  eval radiusSecret="\$SSID${ssid}_RADIUS_SECRET"
  uci set $uciKey.key="$radiusSecret"
else
  eval ssidKey="\$SSID${ssid}_KEY"
  if [ -z "$ssidKey" ] ; then
    uci set $uciKey.encryption=none
  else
    uci set $uciKey.encryption="psk2+aes"
    uci set $uciKey.key="$ssidKey"
  fi
fi

[ "$WIRELESS_WMM" != 1 ] && uci set $uciKey.wmm=1

eval macFilter="\$SSID${ssid}_MAC_FILTER_ENABLED"
if [ "$macFilter" == 1 ] ; then
  eval policy="\$SSID${ssid}_MAC_FILTER_POLICY"
fi
[ "$policy" == allow ] || policy=deny
uci set $uciKey.macfilter=$policy
uci set $uciKey.macfile="/etc/persistent/ssid${ssid}.maclist"

eval radioEnabled="\$SSID${ssid}_ENABLE_RADIO${modeSuffix}"
[ -z "$radioEnabled" ] && radioEnabled=1
[ "$radioEnabled" == 1 ] && disabled=0 || disabled=1
uci set "$uciKey".disabled=$disabled
