#! /bin/sh
CFG_PATH="/lib/firmware"
FW_PRINTCONST=/sbin/fw_printconst

case "$1" in
start)
	ccode=`fw_printconst ccode | cut -f 2 -d '='`
	regrev=`fw_printconst regrev | cut -f 2 -d '='`
	if [ -z "$ccode" -o -z "$regrev" ]; then
		echo "Country code and/or regulatory domain not written in the const partition: using default (USA)."
	else
		cp $CFG_PATH/config.txt /tmp/config.txt
		cat /tmp/config.txt | grep -v "ccode" | grep -v "regrev" > $CFG_PATH/config.txt
		echo "ccode=$ccode" >> $CFG_PATH/config.txt
		echo "regrev=$regrev" >> $CFG_PATH/config.txt
		rm /tmp/config.txt
		echo "WiFi country and regulatory domain set to $ccode and $regrev"
	fi

	regdom=$($FW_PRINTCONST -n wifiRegulatoryDomain)
	if [ $? == 1 ]; then
		regdom=""
	fi
	case "$regdom" in
	"US")
		ln -sf "$CFG_PATH/nvram_ap6398s_ic.txt" "/lib/firmware/nvram_bcm4359c0_ag.txt"
		;;
	"CN")
		ln -sf "$CFG_PATH/nvram_ap6398s_srrc.txt" "/lib/firmware/nvram_bcm4359c0_ag.txt"
		;;
	"GB" | *)
		ln -sf "$CFG_PATH/nvram_ap6398s_ce.txt" "/lib/firmware/nvram_bcm4359c0_ag.txt"
		;;
	esac
	;;

stop)
	echo "Nothing to do with WiFi country and regulatory domain"
	;;


restart)
	$0 stop
	$0 start
	;;

*)

	echo "Usage: /etc/init.d/init-wifi-country-region {start|stop|restart}"
	exit 1
esac
