#!/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/network.sh
source $SCRIPT/utils/wifi.sh
source $SCRIPT/utils/hotspot.sh

radioId="$1"
if [ -z "$radioId" ] ; then
  echo "Invalid radio $radioId" && exit
fi

radioName=`getRadioName $radioId`
radioMode=`getRadioMode $radioId`
mode=`[ -z "$radioMode" ] || echo "_${radioMode}"`
[ "$mode" == "_5G2" ] && mode=_5G

isMode24() {
  [ -z "$radioMode" ] && echo 1
}

isMode50() {
  [ ! -z "$radioMode" ] && echo 1
}

echo "Wireless config radio $radioId mode $radioMode"

uciKey="wireless.${radioName}"

uci set $uciKey.disabled="0"

eval channel="\$WIRELESS_CHANNEL${mode}"
if [ -z "$channel" ] ; then
  [ `isMode24` ] && channel=6 || channel=auto
fi

uci set $uciKey.channel="$channel"

eval htMode="\$WIRELESS_HTMODE${mode}"
if [ `isMode24` ] ; then
  [ -z "$htMode" ] && htMode="HT40"
else
  [ -z "$htMode" ] && htMode="VHT80"
fi
uci set $uciKey.htmode="$htMode"

eval power="\$WIRELESS_POWER${mode}"
[ ! -z "$power" ] && uci set $uciKey.txpower="$power"


# WIRELESS - SSID DEBUG
if [ `isMode24` ] ; then
  uci -q del wireless.debug
  uci set wireless.debug=wifi-iface
  uci set wireless.debug.device="$radioName"
  uci set wireless.debug.mode=ap
  uci set wireless.debug.ifname=debug0
  uci set wireless.debug.network=debug
  uci set wireless.debug.encryption="psk2+aes"

  wanMac=`getWanMac | awk -F ':' '{print $5 $6}'`
  uci set wireless.debug.key="@p0fflin3${wanMac}"
  uci set wireless.debug.ssid="AP-OFFLINE-$wanMac"
  uci set wireless.debug.disabled=1
fi
