#!/bin/sh

. /lib/functions/network.sh
help()
{
    cat <<_HELP_
Setup virtual AP.
Usage: $0 {set|stop} [-channel CH] [-hwmode MODE ][-htmode MODE ] [-name NAME ][-txpower dBm][-radio N]

        -channel CH # WIFI Radio Frequency Channel CH:1~13
        -hwmode MODE # 11b, 11g, and 11a
        -htmode MODE # possible values are: HT20, HT40-, HT40+, HT40, or VHT20, VHT40, VHT80, VHT160, NOHT disables 11n
        -alias NAME # Optional，Radio alias name
        -radio N # radio enum N:0~1
        -txpower dBm # Specifies the transmission power in dBm
Example:
    $0 set -channel 11 -hwmode 11n -htmode HT20 -name radio0 -txpower 20 -radio 0
    $0 stop -radio 0 
_HELP_
}

if [ $# -lt 3 ] ;then 
	help;
	exit 1;
fi

case "$1" in
    set)action="$1";; 
    stop)action="$1";;
    *) help; exit 1;;
esac
shift 1


disable_radio()
{
uci batch << EOF
set wireless.$name.disabled='1'
commit wireless
EOF
}


if [ "$action" == "stop" ];then
case $1 in
    -radio) 
	name="radio""$2";shift 2
	disable_radio
	exit;;
    *);;
esac

fi


while [ -n "$1" ]; do
    case $1 in
        -alias) alias="$2";shift 2;;
        -channel) channel="$2";shift 2;;
        -hwmode) hwmode="$2";shift 2;;
        -htmode) htmode="$2";shift 2;;
        -txpower) txpower="$2";shift 2;;
	    -radio) name="radio""$2";shift 2;;
        -S) no_restart='1';shift 1;;
        --) shift;break;;
        -*) help;exit 1;;
        *) break;;
    esac
done


set_radio()
{

uci batch << EOF
set wireless."$name".txpower="$txpower"
set wireless."$name".hwmode="$hwmode"
set wireless."$name".htmode="$htmode"
set wireless."$name".alias="$alias"
set wireless."$name".channel="$channel"
set wireless."$name".disabled="0"
commit wireless
EOF
}


radio_section=`uci get wireless."$name"`
if [ -z "$radio_section" ];then
	echo "Error not radio:$name"
	exit 1
fi

set_radio 

if [ -z "$no_restart" ]; then
    /etc/init.d/network reload
fi

exit 0
