#!/bin/sh

#/sbin/get_default_channel $wireless_region $band $htmode

if [ "$#" -lt "3" ];then
	echo "/sbin/get_default_channel region_config_value band htmode" >/dev/console
	exit 1
fi

channel_list_file="/etc/channel_regulations.conf"
region_cfgvalue=$1 
band_gui=$2
htmode=$3

output_print()
{
	echo "$1"
	echo "$1" >/tmp/default_channel
	exit 0
}

case $band_gui in
	2G|2g|wl)
		output_print "0"
	;;
	5G1|5g1|wla)
		band="5G"
	;;
	5G|5g|wla_2nd)
		if [ "$(/bin/config get radio_number)" = "0x3" ]; then
			band="5G"
		else
			band="5G2"
		fi
	;;
esac

list_default="$(cat $channel_list_file | grep "^$region_cfgvalue" | grep 5G | grep $htmode |  awk -F'],' '{print $2}')"
if [ "$(/bin/config get radio_number)" = "0x3" ]; then
	default_channel="$(echo $list_default | awk -F"," '{print $1}')"
else
	if [ "$band" = "5G" ];then
		default_channel="$(echo $list_default | awk -F"," '{print $2}' | awk '{print $1}')"
	else
		default_channel="$(echo $list_default | awk -F"," '{print $2}' | awk '{print $2}')"
	fi
fi

list_channels=$(cat $channel_list_file | grep "^$region_cfgvalue" | grep $htmode | grep 5G | awk -F"[][]" '{print $2}' | sed -e 's/[^0-9 ]//g')
if [ -z "$list_channels" ];then
	output_print $default_channel
else
	if [ -n "$(echo $list_channels | grep -o $default_channel)" ];then
		output_print $default_channel
	else
		if [ "$band" = "5G2" ];then
			first_channel="$(echo $list_channels | grep -o "1.." | sort | head -1)"
			[ -z "$first_channel" ] && first_channel="$(echo $list_channels | sed 's/ /\n/g' | sort | head -1)"
		else
			first_channel="$(echo $list_channels | sed 's/ /\n/g' | sort -n | head -1)"
		fi
		output_print $first_channel
	fi
fi

