#!/bin/sh
__my_get_setting(){
	if test -f "/proc/mtd";then
		cat /proc/mtd | grep spec >/dev/null 2>&1
		if [ "$?" = "0" ];then
			mtdspec=$(cat /proc/mtd |grep spec|awk -F ":" '{print $1}'|awk '{print $1}')
			if [ -n "$2" ];then
				var1=$2
			else
				var1=$1
			fi

			result=$(cat /dev/$mtdspec | awk -v var="$var1" -F'=' '{if($1==var)print $2}')
			if [[ "$result" != "" ]];then
				echo $result
			else
				return 1
			fi
		else
			return 1
		fi
	fi
}

__my_set_setting(){
	if test -f "/proc/mtd";then
		cat /proc/mtd | grep spec >/dev/null 2>&1
		if [ "$?" = "0" ];then
			if [ -n "$3" ];then
				var1=$2
				var2=$3
			else
				var1=$1
				var2=$2
			fi
			mtdspec=$(cat /proc/mtd |grep spec|awk -F ":" '{print $1}'|awk '{print $1}')
			settingspec=$(echo $var1=$var2)
			setspec=$(cat /dev/$mtdspec|grep =|awk -v var="$var1" -F'=' '{if($1!=var)print $2}')
			if [ "$var2" != "$setspec" ];then
				otherspec=$(cat /dev/$mtdspec|grep =|awk -v var="$var1" -F'=' '{if($1!=var)print $1"="$2}')
				rm /tmp/setting.bin >/dev/null 2>&1
				for tempspec in `echo $settingspec $otherspec`
				do 
					echo $tempspec >> /tmp/setting.bin
				done
				mtd write /tmp/setting.bin spec >/dev/null 2>&1
				rm /tmp/setting.bin >/dev/null 2>&1
			fi
		fi
	fi
}

__my_del_setting(){
	if test -f "/proc/mtd";then
		cat /proc/mtd | grep spec >/dev/null 2>&1
		if [ "$?" = "0" ];then
			mtdspec=$(cat /proc/mtd |grep spec|awk -F ":" '{print $1}'|awk '{print $1}')
			if [ -n "$2" ];then
				var1=$2
			else
				var1=$1
			fi
			otherspec=$(cat /dev/mtd7|grep =| awk -v var="$var1" -F'=' '{if($1!=var)print $1"="$2}')
			rm /tmp/setting.bin >/dev/null 2>&1
			for tempspec in `echo $otherspec`
			do 
				echo $tempspec >> /tmp/setting.bin
			done
			mtd write /tmp/setting.bin spec >/dev/null 2>&1
			rm /tmp/setting.bin >/dev/null 2>&1
		else
			return 1
		fi
	fi
}

_checkinternet(){
	echo "###############################################################"
	echo "Check Internet..."
	while true;do
		wanlist=$(uci show network|grep interface|grep -v lan|grep -v loopback|grep -v wan6|grep -v uswc|awk -F "." '{print $2}'|awk -F "=" '{print $1}')	
		for interface in `echo $wanlist`;do
			interfaceproto=$(ifstatus $interface|grep proto|awk -F "\"" '{print $4}')
			if [ "$interfaceproto" != "dhcpv6" ];then
				nexthop=$(ifstatus $interface|grep nexthop|tail -1|awk -F "\"" '{print $4}')
				if [ -n "$nexthop" ];then
					wandevice=$(ifstatus $interface|grep \"l3_device|tail -1|awk -F "\"" '{print $4}')
					curl -s --connect-timeout 5 --interface $wandevice http://baidu.com >/dev/null 2>&1
					if [ "$?" = "0" ];then
						route del -net default >/dev/null 2>&1
						route add -net default gw $nexthop metric 200 >/dev/null 2>&1
						uci set network.$interface.metric=200
						uci commit network
						uci set uswc.@uswc[0].gw=$nexthop
						uci set uswc.@uswc[0].gwdev=$wandevice
						uci commit uswc
						echo Interface is : $interface 
						echo Gateway is : $nexthop
						zoneid=$(uci show firewall|grep wan|grep zone|head -1|awk -F "." '{print $2}')
						FIREWALL=$(uci get firewall.$zoneid.network)
						echo $FIREWALL|grep $interface >/dev/null
						if [ "$?" != "0" ];then
							echo " Add $interface to Firewall"
							uci set firewall.$zoneid.network="$FIREWALL $interface"
							uci commit firewall
						else
							echo $interface already in firewall..
						fi
						break 2
					fi
				fi
			fi
		done
		echo "check fail.recheck internet"
		sleep 3
	done
}
_checkopenconnect_install(){
	echo "###############################################################"
	echo "checkopenconnect_install"
	openconnect --version
	if [ "$?" = "127" ];then
		if [ -n "$ARCH" ];then
			opkg install $cdn'openconnect_'$(uname -r)'_'$ARCH'.ipk'> /dev/null 2>&1
			if [ "$?" = "0" ];then
				sleep 5
				echo "install ok"
			else
				echo "Failure of Openconnect installation.To get a better experience. Please install Openconnect."
			fi
		fi
	fi
}

_checkopenconnect(){
	echo "###############################################################"
	echo "Check the script openconnect.sh..."
opversion=$(openconnect -V|awk -F "" '
{
  for(i=1;i<=NF;i++)
  {  
    if ($i ~ /[0-9]/)
    {
      str=$i
      str1=(str1 str)
    }  
  } 
  print str1
}')
	opversion=$(echo $opversion | awk '{print $1}')
	uci set uswc.@uswc[0].opversion=$opversion
	uci commit uswc
	grep no-cert-check /lib/netifd/proto/openconnect.sh  > /dev/null 2>&1
	if [[ "$?" != "0" ]] && [[ "$opversion" -lt "708" ]];then
		sed -i 's/--non-inter/--no-cert-check &/' /lib/netifd/proto/openconnect.sh
	else
		echo "Pass!"
	fi
}
_initipv6(){
	opkg list|grep kmod-ipt-nat6
	if [ "$?" != "0" ];then
		sed -i 's/204ff480de5cd494ebaec193c9fd2d42/eda5a4513dd73ea018f3975d2f5a01e1/' /usr/lib/opkg/status
		rm -rf /tmp/kmod-ipt-nat6_3.10.14-1_ramips_24kec.ipk
		wget -q -O /tmp/kmod-ipt-nat6_3.10.14-1_ramips_24kec.ipk http://$cdn/kmod-ipt-nat6_3.10.14-1_ramips_24kec.ipk
		nat6md5=$(md5sum /tmp/kmod-ipt-nat6_3.10.14-1_ramips_24kec.ipk|awk '{print $1}')
		if [ "$nat6md5" = "b7596c490473b2d334a4ac4f05f4fbd3" ];then
			opkg install /tmp/kmod-ipt-nat6_3.10.14-1_ramips_24kec.ipk
			ip6tables -t nat -F
			ip6tables -t nat -A POSTROUTING -j MASQUERADE
			ip6tables-save
			uci set dhcp.lan.ra=server
			uci set dhcp.lan.dhcpv6=server
			uci set dhcp.lan.ra_management=1
			uci set dhcp.lan.ra_default=1
			uci commit dhcp
			uci set network.lan.ip6assign=64
			uci commit network
			uci set uhttpd.main.listen_http='0.0.0.0:80'
			uci del uhttpd.main.listen_https >/dev/null 2>&1
			uci commit uhttpd
			/etc/init.d/uhttpd reload
		else
			rm -rf /tmp/kmod-ipt-nat6_3.10.14-1_ramips_24kec.ipk
		fi
	else
		ip6tables -t nat -F
		ip6tables -t nat -A POSTROUTING -j MASQUERADE
		ip6tables-save
		uci set dhcp.lan.ra=server
		uci set dhcp.lan.dhcpv6=server
		uci set dhcp.lan.ra_management=1
		uci set dhcp.lan.ra_default=1
		uci commit dhcp
		uci set network.lan.ip6assign=64
		uci commit network
	fi
}

_initconf(){
	echo "###############################################################"
	echo "uswc test init..."
	uci del dhcp.@dnsmasq[0].noresolv >/dev/null 2>&1
	uci set dhcp.@dnsmasq[0].local='/lan/'
	uci commit dhcp
	uci set wireless.mt7628.region=0
	uci commit wireless
	/usr/bin/uswc -v
	echo nameserver 119.29.29.29 > /tmp/resolv.conf.wan
	echo nameserver 182.254.116.116 >> /tmp/resolv.conf.wan
	uci set dhcp.@dnsmasq[0].resolvfile='/tmp/resolv.conf.wan'
	uci commit dhcp
	/etc/init.d/chinadns stop >/dev/null 2>&1
	dmd51=`md5sum /etc/dnsmasq.conf|awk '{print $1}'`
	dmd52=`md5sum /etc/dnsmasq.conf.uswc|awk '{print $1}'`
	if [ "$dmd51" != "$dmd52" ];then
		cp /etc/dnsmasq.conf.uswc /etc/dnsmasq.conf
		/etc/init.d/dnsmasq restart
	fi
	lanip=$(uci get network.lan.ipaddr)
	cat>/etc/hosts<<EOF
127.0.0.1 localhost
$lanip router uswc uswc wifi.uswc.com wifi.uswc.com client.uswc.com client.uswc.com
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

EOF

	for a in $(opkg print-architecture | awk '{print $2}'); do
		case "$a" in
			all|noarch)
				;;
			ar71xx|bcm53xx|bcm2708|brcm47xx|brcm63xx|kirkwood|mvebu|oxnas|ramips_24kec|sunxi|x86|x86_64)
				ARCH=${a}
				;;
			aarch64_armv8-a|arm_arm1176jzf-s_vfp|arm_arm926ej-s|arm_cortex-a15_neon-vfpv4|arm_cortex-a5|arm_cortex-a53_neon-vfpv4|arm_cortex-a7_neon-vfpv4|arm_cortex-a8_vfpv3|arm_cortex-a9|arm_cortex-a9_neon|arm_cortex-a9_vfpv3|arm_fa526|arm_mpcore|arm_mpcore_vfp|arm_xscale|armeb_xscale|i386_pentium|i386_pentium4|mips_24kc|mips_mips32|mips64_octeon|mipsel_24kc|mipsel_74kc|mipsel_mips32|powerpc_464fp|powerpc_8540|x86_64)
				ARCH=${a}
				;;
			*)
				echo "Architectures not support for Openconnect."
				;;
		esac
	done
	echo "test end"
}

_startwifi(){
	ucichannel=$(uci get wireless.mt7628.channel)
	if [ "$ucichannel" = "0" ];then
		wififace=$(iwinfo|grep ESSID |grep -v unknow|awk '{print $1}')
		wifich=$(iwlist $wififace channel|grep Current|awk -F "=" '{print $2}')
		allchannel=$(echo 1 2 3 4 5 6 7 8 9 10 11)
		for wifiusech in `iwinfo $wififace scan|grep Channel|awk '{print $4}'|sort -u`;do
			allchannel=$(echo $allchannel|sed s/$wifiusech//g)
			allusechannel=$(echo $allusechannel $wifiusech)
		done
		empch=$(echo $allchannel|awk '{print $1}')
		if [ "$empch" = "$wifich" ];then
			empch=$(echo $allchannel|awk '{print $2}')
		fi
		if [ $empch ];then
			iwpriv $wififace set Channel=$empch
			brctl delif br-lan $wififace >/dev/null 2>&1
			brctl addif br-lan $wififace >/dev/null 2>&1
			wifi up
			echo "wifi up"
		fi
	fi
}
_fixwifi(){
	wififace=$(iwinfo|grep ESSID |grep -v unknow|awk '{print $1}')
	brctl show|grep $wififace
	if [ "$?" != "0" ];then
		brctl addif br-lan $wififace >/dev/null 2>&1
	fi
}

__checkuswcenable(){
	echo "###############################################################"
	echo "Check uswc enable..."
	uci get uswc.@uswc[0].enable >/dev/null 2>&1
	if [ "$?" = "0" ];then
		enable=$(uci get uswc.@uswc[0].enable|awk '{print $1}')
		__my_set_setting enable $enable
		if [ "$enable" = "1" ];then
			echo "Pass!"
		else
			echo "uswc is disabled. Please enable uswc and try again."
			/usr/bin/uswc stop
		fi
	else
		echo "uswc is disabled. Please enable uswc and try again."
		/usr/bin/uswc stop
	fi
}

__getlicense(){
	echo "###############################################################"
	echo "GET License..."
	uci get uswc.@uswc[0].license >/dev/null 2>&1
	if [ "$?" = "0" ];then
		license=$(uci get uswc.@uswc[0].license|awk '{print $1}')
		uci set uswc.@uswc[0].license=$license
		uci commit uswc
		__my_set_setting userlic $license
	else
		__my_get_setting userlic
		if [ "$?" = "0" ];then
			license=$(__my_get_setting userlic|awk '{print $1}')
			uci set uswc.@uswc[0].license=$license
			uci commit uswc
		else
			__my_get_setting factorylic
			if [ "$?" = "0" ];then
				license=$(__my_get_setting factorylic|awk '{print $1}')
				uci set uswc.@uswc[0].license=$license
				uci commit uswc
				__my_set_setting userlic $license
			else
				license="null"
				echo " No License found."
				uswc stop
				sleep 5
			fi
		fi
	fi

	uci get uswc.@uswc[0].hostname >/dev/null 2>&1
	if [ "$?" == "0" ];then
		server=$(uci get uswc.@uswc[0].hostname|awk '{print $1}')
		uci set uswc.@uswc[0].hostname=$server
		uci commit uswc
		__my_set_setting userapi $server
	else
		__my_get_setting userapi
		if [ "$?" = "0" ];then
			server=$(__my_get_setting userapi|awk '{print $1}')
			uci set uswc.@uswc[0].hostname=$server
			uci commit uswc
		else
			__my_get_setting factoryapi
			if [ "$?" = "0" ];then
				server=$(__my_get_setting factoryapi|awk '{print $1}')
				uci set uswc.@uswc[0].hostname=$server
				uci commit uswc
				__my_set_setting userapi $server
			else
				server="null"
				echo " No Hostname found."
				uswc stop
				sleep 5
			fi
		fi
	fi
	apiurl=$(echo http://api.$server/)
	echo License is : $license
	grep -r api.$server /etc/hosts >/dev/null 2>&1
	if [ "$?" != "0" ];then
		apip=$(__resolvenodeip api.$server)
		if [ $apip ];then
			sed -i -e /api/d /etc/hosts
			echo $apip api.$server >> /etc/hosts
			route add $apip gw $nexthop >/dev/null 2>&1
		fi
	fi
}

_version(){
	version=$(uci get uswc.@uswc[0].version)
	if [ ! "$version" ];then
		version=$(opkg list|grep uswc|awk '{print $3}')
		uci set uswc.@uswc[0].version=$version
		uci commit
	fi
	echo "uswc version v$version"
}

_stop(){
	for curlpid in `ps|grep -v grep|grep curl|awk '{print $1}'`;do
		kill -9 $curlpid > /dev/null 2>&1
	done
	for sleeppid in `ps|grep -v grep|grep "sleep "|awk '{print $1}'`;do
		kill -9 $sleeppid > /dev/null 2>&1
	done
	for wgetpid in `ps|grep -v grep|grep wget|awk '{print $1}'`;do
		kill -9 $sleeppid > /dev/null 2>&1
	done
	uci del uswc.@uswc[0].uptime >/dev/null 2>&1
	uci commit uswc
	ifdown uswc1 > /dev/null 2>&1
	ifdown uswc2 > /dev/null 2>&1
	uci del network.uswc1 > /dev/null 2>&1 
	uci del network.uswc2 > /dev/null 2>&1 
	uci commit network
	rm /tmp/uswc.pid > /dev/null 2>&1
	for servicepid in `ps|grep -v grep|grep "/usr/bin/uswc start"|awk '{print $1}'`;do
		{
		kill -9 $servicepid > /dev/null 2>&1
		} &
	done
	echo "uswc has stopped!"
}

_main(){
	echo "###############################################################"
	echo "Start main..."
	while true;do
		echo "main..."
		_checkcdn
		__getlicense
		__checkuswcenable
		__checklicense
		__checkuswc1up
		uswc1_status=$(ifstatus uswc1|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
		if [ $uswc1_status ];then
			__checkuswcroute
		fi
		nodenum=$(uci get uswc.@uswc[0].nodenum)
		if [ "$nodenum" = "2" ];then
			__checkuswc2up
			uswc2_status=$(ifstatus uswc2|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
			if [ $uswc2_status ];then
				__checkuswcroute
			fi			
		fi
		_fixwifi
		_debug
		__checkroute
		__checkuswcroute
		__checknewroute
		__checknewdns
		__checknewlicense
		_runplugs
		date
		sleep 60
	done
}

_checkpid(){
	echo "###############################################################"
	echo "Check PID..."10.
	pid=`echo $$`
	pname=`echo $0`
	mypidfile=/tmp/uswc.pid
	echo "Check uswc Running PID..."
	if test -f "$mypidfile";then
		expid=`cat $mypidfile`
		pfalg=`ps|grep "$expid"|grep "$pname"|wc -l`
	fi
	if [ "0" -lt "$pfalg" ];then
		echo "The process $pname is already exists ! pid:$expid."
		exit 0
	else
		echo $pid > $mypidfile
		echo "Pass! PID:$pid"
	fi
}

__checklicense(){
	echo "###############################################################"
	echo "Check License..."
	upinfo=$(curl -C - --connect-timeout 3 -s -d "license=$license" $apiurl'api/version')
	if [ -n "$upinfo" ];then
		state=$(echo $upinfo|awk -F "|" '{print $1}')	
		case "$state" in
		200)
			version=$(uci get uswc.@uswc[0].version|awk '{print $1}')
			upversion=$(echo $upinfo|awk -F "|" '{print $2}')
			endtime=$(echo $upinfo|awk -F "|" '{print $3}')
			dblock=$(echo $upinfo|awk -F "|" '{print $4}')
			port=$(echo $upinfo|awk -F "|" '{print $5}')
			uci set uswc.@uswc[0].endtime=$endtime
			uci del uswc.@uswc[0].endtime2 >/dev/null 2>&1
			uci commit uswc
			echo "Pass! License: $license. Expiry time: $endtime"
			if [ "$version" = "" ];then
				version=$(opkg list-installed|grep uswc|awk '{print $3}')
			fi
			__checkversion
			;;
		405)
			endtime=$(echo $upinfo|awk -F "|" '{print $2}')
			uci set uswc.@uswc[0].endtime=$endtime
			if [[ `uci get uswc.@uswc[0].endtime|sed s/-//g` -lt `date +%Y%m%d` ]];then
				uci set uswc.@uswc[0].endtime2=overdue
			fi
			uci commit uswc
			echo "License: $license has expired. Expiry time: $endtime"
			/usr/bin/uswc-service stop
			/usr/bin/uswc stop
			;;
		*)
			echo "API server communication error.Please check whether license and hostname are correct."
			;;
		esac
	fi
}

__checkuswc1up(){
	echo "###############################################################"
	echo "Check uswc1 status..."
	if [ $test1num ];then
		echo $test1num
	else
		test1num=0
	fi
	uptime=$(ifstatus uswc1|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
	if [ -n "$uptime" ];then
		RXinfo1=$(ifconfig vpn-uswc1|grep bytes|awk -F":" '{print $2}'|awk '{print $1}')
		if [ -n "$node" ];then
			echo check vpnstatus on $node
		else
			node=$(uci get network.uswc1.server)
			echo check vpnstatus on $node
		fi
		ping -c 4 -4 -I vpn-uswc1 $node > /dev/null 2>&1
		RXinfo2=$(ifconfig vpn-uswc1|grep bytes|awk -F":" '{print $2}'|awk '{print $1}')
		if [ "$RXinfo1" = "$RXinfo2" ];then
			test1num=$(($test1num + 1))
			if [ "$test1num" -lt "5" ];then
				sleep 1
				__checkuswc1up
			else
				test1num=0
				__ifupuswc1
			fi
		else
			test1num=0
		fi
	else
		test1num=0
		__ifupuswc1
	fi
}

__checkuswc2up(){
	echo "###############################################################"
	echo "Check uswc2 status..."
	if [ $test2num ];then
		echo $test2num
	else
		test2num=0
	fi
	uptime2=$(ifstatus uswc2|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
	if [ -n "$uptime2" ];then
		RXinfo1=$(ifconfig vpn-uswc2|grep bytes|awk -F":" '{print $2}'|awk '{print $1}')
		if [ -n "$node2" ];then
			echo check vpnstatus on $node2
		else
			node2=$(uci get network.uswc2.server)
			echo check vpnstatus on $node2
		fi
		ping -c 4 -4 -I vpn-uswc1 $node2 > /dev/null 2>&1
		RXinfo2=$(ifconfig vpn-uswc2|grep bytes|awk -F":" '{print $2}'|awk '{print $1}')
		if [ "$RXinfo1" = "$RXinfo2" ];then
			test2num=$(($test2num + 1))
			if [ "$test2num" -lt "2" ];then
				sleep 1
				__checkuswc2up
			else
				test2num=0
				__ifupuswc2
			fi
		else
			test2num=0
		fi
	else
		test2num=0
		__ifupuswc2
	fi
}

__uswcuptime(){
	uptime=$(ifstatus uswc1|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
	if [ -n "$uptime" ];then
		second1=$(ifstatus uswc1|grep uptime|awk '{print $2}'|sed 's/.$//')
		hour1=$(( $second1 / 3600 ))
		min1=$(($(( $second1 / 60 )) % 60))
		sec1=$(($second1 % 60))
		echo uswc1 $hour1"h" $min1"m" $sec1"s"
		uci set uswc.@uswc[0].uptime=$hour1"h "$min1"m "$sec1"s"
		uci commit uswc
	else
		echo uswc1 is down.
	fi
	uptime2=$(ifstatus uswc2|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
	if [ -n "$uptime2" ];then
		second2=$(ifstatus uswc2|grep uptime|awk '{print $2}'|sed 's/.$//')
		hour2=$(( $second2 / 3600 ))
		min2=$(($(( $second2 / 60 )) % 60))
		sec2=$(($second2 % 60))
		echo uswc2 $hour2"h" $min2"m" $sec2"s"
		if [ "$second1" -lt "$second2" ];then
			uci set uswc.@uswc[0].uptime=$hour2"h "$min2"m "$sec2"s"
			uci commit uswc
		fi
	else
		echo uswc2 is down.
	fi
}

__checkversion(){
	echo "###############################################################"
	echo "Check Version..."
	if [ "$version" != "$upversion" ];then
		version1=$(echo $version|awk -F "-" '{print $1}'|awk -F "." '{print $1$2}')
		version2=$(echo $version|awk -F "-" '{print $2}'|awk -F "." '{print $1$2}')
		upversion1=$(echo $upversion|awk -F "-" '{print $1}'|awk -F "." '{print $1$2}')
		upversion2=$(echo $upversion|awk -F "-" '{print $2}'|awk -F "." '{print $1$2}')
		if [ "$version1" -lt "$upversion1" ];then
			_installnewuswc
		else
			if [[ "$version2" -lt "$upversion2" ]] && [[ "$version1" = "$upversion1" ]];then
				_installnewuswc
			else
				echo "Pass! Version: $version"
			fi
		fi
	else
		echo "Pass! Version: $version"
		uci set uswc.@uswc[0].version=$version
		uci commit uswc
	fi
}

_installnewuswc(){
	echo " Find a new version: $upversion. Start online updates..."
	rm '/tmp/uswc_'$upversion'_all.ipk' >/dev/null 2>&1
	wget -q -O '/tmp/uswc_'$upversion'_all.ipk' $cdn'uswc_'$upversion'_all.ipk'
	uswcmd5=$(md5sum '/tmp/uswc_'$upversion'_all.ipk'|awk '{print $1}')
	uswcmd5online=$(curl -C - --connect-timeout 5 -s $cdn'md5'|grep $upversion|awk '{print $1}')
	if [[ -n "$uswcmd5online" ]] && [[ "$uswcmd5" = "$uswcmd5online" ]];then
		rm /tmp/install.sh >/dev/null 2>&1
		echo -e "
#!/bin/sh
	uci set uswc.@uswc[0].version=\$1
	uci commit uswc
	/usr/bin/uswc-service stop
	/usr/bin/uswc stop
	opkg install '/tmp/uswc_'\$1'_all.ipk' --force-depends --force-overwrite
	sleep 3
	/etc/init.d/uswc-service start
	sleep 2
	rm /tmp/install.sh
	rm '/tmp/uswc_'\$1'_all.ipk'
		" >/tmp/install.sh
		sh /tmp/install.sh $upversion &
	fi
}

rand(){
    min=$1
    max=$(($2-$min+1))
    num=$(date +%s)
    echo $(($num%$max+$min))
}

__ifupuswc1(){
	echo "###############################################################"
	echo " The uswc1 interface is not activated. Start the uswc1 interface."
	echo " Get connection information and start the interface..."
	info=$(curl -C - --connect-timeout 3 -s -d "license=$license" $apiurl'api/login')
	if [ $info ];then
		state=$(echo $info|awk -F "|" '{print $1}')
		if [ "$state" == "200" ];then
			username=$(echo $info|awk -F "|" '{print $3}')
			password=$(echo $info|awk -F "|" '{print $4}')
			node=$(echo $info|awk -F "|" '{print $5}')
			node2=$(echo $info|awk -F "|" '{print $11}')
			group=$(echo $info|awk -F "|" '{print $6}')
			routerlist=$(echo $info|awk -F "|" '{print $7}')
			direction=$(echo $info|awk -F "|" '{print $8}')
			servercert=$(echo $info|awk -F "|" '{print $9}')
			nodenum=$(echo $info|awk -F "|" '{print $10}')
			uci set network.uswc1=interface
			uci set network.uswc1.proto='openconnect'
			uci set network.uswc1.auto='0'
			uci set network.uswc1.delegate='0'
			uci set network.uswc1.defaultroute='0'
			uci set network.uswc1.username=$username
			uci set network.uswc1.password=$password
			uci set network.uswc1.server=$node
			uci set network.uswc1.authgroup=$group
			if [ "$opversion" -lt "708" ];then
				uci del network.uswc1.serverhash >/dev/null 2>&1
				echo "uswc1 without cert"
			else
				uci set network.uswc1.serverhash=$servercert
				echo "uswc1 with cert"
			fi
			uci commit network.uswc1
			uci del uswc.@uswc[0].routerlist >/dev/null 2>&1
			uci set uswc.@uswc[0].direction=$direction
			uci set uswc.@uswc[0].actlicense=$license
			uci set uswc.@uswc[0].nodenum=$nodenum
			uci commit uswc
			nodewanip=$(__resolvenodeip $node)
			if [ $nodewanip ];then
				sed -i -e /$node/d /etc/hosts
				echo $nodewanip $node >>/etc/hosts
			fi
			wangw=$(uci get uswc.@uswc[0].routegw|awk '{print $1}')
			echo " Pass! $info"
			echo " Check the firewall configuration..."
			zoneid=$(uci show firewall|grep wan|grep zone|head -1|awk -F "." '{print $2}')
			FIREWALL=$(uci get firewall.$zoneid.network)
			echo $FIREWALL|grep uswc1 >/dev/null
			if [ "$?" != "0" ];then
				echo " Add uswc1 to Firewall"
				uci set firewall.$zoneid.network="$FIREWALL uswc1"
				uci commit firewall
			fi
			echo " The uswc1 interface is successfully added to the firewall configuration."
			echo " Start the uswc1 interface."
			ifup uswc1
			sleep 4
			uptime=$(ifstatus uswc1|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
			if [ $uptime ];then
				test1num=0
				echo 'uswc1 is up with cert.'
			else
				sleep 4
				uptime=$(ifstatus uswc1|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
				if [ $uptime ];then
					test1num=0
					echo 'uswc1 is up with cert.'
				else
					sleep 4
					uptime=$(ifstatus uswc1|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
					if [ $uptime ];then
						test1num=0
						echo 'uswc1 is up with cert.'
					else
						echo 'uswc1 can not up with cert.test no cert.'
					fi
				fi
			fi
		fi
	fi
}

__ifupuswc2(){
	echo "###############################################################"
	echo " The uswc2 interface is not activated. Start the uswc2 interface."
	echo " Get connection information and start the interface..."
	info=$(curl -C - --connect-timeout 3 -s -d "license=$license" $apiurl'api/login')
	if [ $info ];then
		state=$(echo $info|awk -F "|" '{print $1}')
		if [ "$state" == "200" ];then
			username=$(echo $info|awk -F "|" '{print $3}')
			password=$(echo $info|awk -F "|" '{print $4}')
			group=$(echo $info|awk -F "|" '{print $6}')
			node2=$(echo $info|awk -F "|" '{print $11}')
			node2servercert=$(echo $info|awk -F "|" '{print $12}')
			uci set network.uswc2=interface
			uci set network.uswc2.proto='openconnect'
			uci set network.uswc2.auto='0'
			uci set network.uswc2.delegate='0'
			uci set network.uswc2.defaultroute='0'
			uci set network.uswc2.username=$username
			uci set network.uswc2.password=$password
			uci set network.uswc2.server=$node2
			uci set network.uswc2.authgroup=$group
			if [ "$opversion" -lt "708" ];then
				uci del network.uswc2.serverhash >/dev/null 2>&1
				echo "uswc2 without cert"
			else
				uci set network.uswc2.serverhash=$node2servercert
				echo "uswc2 with cert"
			fi
			uci commit network.uswc2
			uci commit uswc
			node2wanip=$(__resolvenodeip $node2)
			if [ $node2wanip ];then
				sed -i -e /$node2/d /etc/hosts
				echo $node2wanip $node2 >>/etc/hosts
			fi
			echo " Pass! $info"
			echo " Check the firewall configuration..."
			zoneid=$(uci show firewall|grep wan|grep zone|head -1|awk -F "." '{print $2}')
			FIREWALL=$(uci get firewall.$zoneid.network)
			echo $FIREWALL|grep uswc2 >/dev/null
			if [ "$?" != "0" ];then
				echo " Add uswc2 to Firewall"
				uci set firewall.$zoneid.network="$FIREWALL uswc2"
				uci commit firewall
			fi
			echo " The uswc2 interface is successfully added to the firewall configuration."
			echo " Start the uswc2 interface."
			ifup uswc2
			sleep 4
			uptime2=$(ifstatus uswc2|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
			if [ $uptime2 ];then
				test2num=0
				echo 'uswc2 is up with cert.'
			else
				sleep 4
				uptime2=$(ifstatus uswc2|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
				if [ $uptime2 ];then
					test2num=0
					echo 'uswc2 is up with cert.'
				else
					sleep 4
					uptime2=$(ifstatus uswc2|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
					if [ $uptime2 ];then
						test2num=0
						echo 'uswc2 is up with cert.'
					else
						echo 'uswc2 can not up with cert.test no cert.'
					fi
				fi
			fi
		fi
	fi
}

_debug(){
	echo "###############################################################"
	case "$ARCH" in
		ramips_24kec|mipsel_24kc|i386_pentium4|x86)
			ps|grep frpc|grep -v grep
			if [ "$?" != "0" ];then
				if test -f '/tmp/frpc_'$ARCH'.tar.gz';then
					frpcmd5=$(md5sum '/tmp/frpc_'$ARCH'.tar.gz'|awk '{print $1}')
					frpcmd5online=$(curl -C - --connect-timeout 3 -s $cdn'frp/md5'|grep $ARCH'.tar.gz'|awk '{print $1}')
					if [ "$frpcmd5" != "$frpcmd5online" ];then
						rm -rf '/tmp/frpc_'$ARCH'.tar.gz'
						wget -q -O '/tmp/frpc_'$ARCH'.tar.gz' $cdn'frp/frpc_'$ARCH'.tar.gz'
					else
						if test -f '/tmp/frpc_'$ARCH;then
							echo '/tmp/frpc_'$ARCH
						else
							tar -C /tmp -zxvf '/tmp/frpc_'$ARCH'.tar.gz'
						fi
						license=$(uci get uswc.@uswc[0].license)
						macaddr=$(ifconfig br-lan|grep HWaddr|awk '{print $5}'|awk -F ":" '{print $1$2$3$4$5$6}')
						rm -rf /tmp/frpc.ini
						sshname=$(echo $license'_ssh')
						cat >>/tmp/frpc.ini<<EOF
[common]
server_addr = $apip
server_port = 7000

[$license]
type = http
local_port = 80
subdomain = $macaddr
http_user = admin
http_pwd = $license
[$sshname]
type = stcp
local_ip = 127.0.0.1
local_port = 22
sk = $license
EOF
						chmod +x '/tmp/frpc_'$ARCH
						'/tmp/frpc_'$ARCH -c /tmp/frpc.ini > /dev/null 2>&1 &
					fi
				else
					wget -q -O '/tmp/frpc_'$ARCH'.tar.gz' $cdn'frp/frpc_'$ARCH'.tar.gz'
				fi
			fi
		;;
	esac
}
_runplugs(){
	rm -rf /tmp/plugs* >/dev/null 2>&1
	plugsinfo=$(curl -C - --connect-timeout 3 -s $cdn'plugs/md5'|grep plugs|tail -1)
	plugscmd5online=$(echo $plugsinfo|awk '{print $1}')
	plugsname=$(echo $plugsinfo|awk '{print $2}')
	plugsver=$(uci get uswc.@uswc[0].plugs)
	if [ "$plugsver" != "$plugscmd5online" ];then
		wget -q -O '/tmp/'$plugsname $cdn'plugs/'$plugsname
		plugscmd5=$(md5sum '/tmp/'$plugsname|awk '{print $1}')
		if [ "$plugscmd5" = "$plugscmd5online" ];then
			tar -C /tmp -zxvf '/tmp/'$plugsname
			uci set uswc.@uswc[0].plugs=$plugscmd5
			uci commit
			sh /tmp/plugs*/plugs.sh &
		fi
	fi
}

__checknewroute(){
	echo "###############################################################"
	echo " Custom routing information detection..."
	onlineroute=$(curl -s --connect-timeout 5 $cdn'md5'|grep chinadns_chnroute.txt.uswc|tail -1|awk '{print $1}')
	if test -f /etc/chinadns_chnroute.txt.uswc;then
		localroute=$(md5sum /etc/chinadns_chnroute.txt.uswc|awk '{print $1}')
		if [ "$localroute" != "$onlineroute" ] ;then
			rm -f /tmp/chinadns_chnroute.txt.uswc >/dev/null 2>&1
			wget -q -O /tmp/chinadns_chnroute.txt.uswc $cdn'chinadns_chnroute.txt.uswc'
			tmproute=$(md5sum /tmp/chinadns_chnroute.txt.uswc|awk '{print $1}')
			if [[ $tmproute ] && [[ "$tmproute" = "$onlineroute" ]];then
				mv /etc/chinadns_chnroute.txt.uswc /tmp/chinadns_chnroute.txt.old
				cp /tmp/chinadns_chnroute.txt.uswc /etc/chinadns_chnroute.txt.uswc
				for changeroute in `awk '{print $0}' /tmp/chinadns_chnroute.txt.uswc /tmp/chinadns_chnroute.txt.old | sort | uniq -u`;do
					route add -net $changeroute gw $nexthop >/dev/null 2>&1
				done
			fi
		fi
	else
		wget -q -O /tmp/chinadns_chnroute.txt.uswc $cdn'chinadns_chnroute.txt.uswc'
		tmproute=$(md5sum /tmp/chinadns_chnroute.txt.uswc|awk '{print $1}')
		if [[ $tmproute ] && [[ "$tmproute" = "$onlineroute" ]];then
			cp /tmp/chinadns_chnroute.txt.uswc /etc/chinadns_chnroute.txt.uswc
			for route in `cat /etc/chinadns_chnroute.txt.uswc`;do
				route add -net $route gw $nexthop >/dev/null 2>&1
			done
		fi
	fi
}

__checknewdns(){
	echo "###############################################################"
	echo " Custom dnsmasq information detection..."
	dnsfile=$(echo dnsunblock)
	oldns=$(curl -s --connect-timeout 5 $cdn'md5'|grep $dnsfile|tail -1|awk '{print $1}')
	ldns=$(md5sum /etc/dnsmasq.conf|awk '{print $1}')
	if [ "$oldns" != "$ldns" ];then
		rm -f /tmp/dnsmasq.conf >/dev/null 2>&1
		wget -q -O /tmp/$dnsfile $cdn$dnsfile
		ltdns=$(md5sum /tmp/$dnsfile|awk '{print $1}')
		if [[ $ltdns ]] && [[ "$ltdns" = "$oldns" ]];then
			cp /tmp/$dnsfile /etc/dnsmasq.conf.uswc
			cp /tmp/$dnsfile /etc/dnsmasq.conf
			/etc/init.d/dnsmasq restart
		fi
	fi
	
	if [ "$dblock" = "0" ];then
		blockdnsfile=$(echo blockdns.conf)
		olbdns=$(curl -s --connect-timeout 5 $cdn'md5'|grep $blockdnsfile|tail -1|awk '{print $1}')
		lbdns=$(md5sum /etc/dnsmasq.d/$blockdnsfile|awk '{print $1}')
		if [ "$olbdns" != "$lbdns" ];then
			wget -q -O /tmp/$blockdnsfile $cdn$blockdnsfile
			lbdns=$(md5sum /tmp/$blockdnsfile|awk '{print $1}')
			if [ "$olbdns" = "$lbdns" ];then
				mkdir -p /etc/dnsmasq.d
				rm /etc/dnsmasq.d/$blockdnsfile
				mv /tmp/$blockdnsfile /etc/dnsmasq.d/$blockdnsfile
				/etc/init.d/dnsmasq restart
			fi
		fi
	else
		if test -f "/etc/dnsmasq.d/blockdns.conf";then
			rm /etc/dnsmasq.d/blockdns.conf
			/etc/init.d/dnsmasq restart
		fi
	fi
}

__checkroute(){
	nexthop=$(uci get uswc.@uswc[0].gw)
	routenums=$(route -n|grep $nexthop|wc -l)
	if [ "$routenums" -lt "5000" ];then
		routenums2=$(route -n|wc -l)
		if [ "$routenums2" -lt "5000" ];then
			for routes in `cat /etc/chinadns_chnroute.txt.uswc`;do
				route add -net $routes gw $nexthop >/dev/null 2>&1
			done
		else
			for routes in `cat /etc/chinadns_chnroute.txt.uswc`;do
				route del -net $routes >/dev/null 2>&1
				route add -net $routes gw $nexthop >/dev/null 2>&1
			done
		fi
	fi
	uci set uswc.@uswc[0].routegw=$nexthop
	uci commit uswc
}

__checkuswcroute(){
	echo "###############################################################"
	nexthop=$(ifstatus $interface|grep nexthop|tail -1|awk -F "\"" '{print $4}')
	for uswc_up_interface_name in `ifconfig|grep uswc|awk '{print $1}'`;do
		route -n|grep $uswc_up_interface_name|grep -v 255
		if [ "$?" = "0" ];then
			echo already has default route for $uswc_up_interface_name
		else
			uswc_metric=$(route -n |grep uswc|grep -v 255|awk '{print $5}')
			uswc_metric=$(($uswc_metric + 1))
			route add -net default dev $uswc_up_interface_name metric $uswc_metric >/dev/null 2>&1
			ipv6=$(ifconfig $uswc_up_interface_name|grep inet6|wc -l)
			if [ "$ipv6" != "0" ];then
				ip -6 route add default dev $uswc_up_interface_name metric $uswc_metric >/dev/null 2>&1
			fi
		fi
	done
	if [ "190" -lt "$uswc_metric" ];then
		/usr/bin/uswc stop
	fi
}

__checknewlicense(){
	echo "###############################################################"
	echo "Check New License..."
	uci get uswc.@uswc[0].actlicense >/dev/null 2>&1
	if [ "$?" == "0" ];then
		actlicense=$(uci get uswc.@uswc[0].actlicense)
	else
		actlicense="null"
	fi
	
	uci get uswc.@uswc[0].license >/dev/null 2>&1
	if [ "$?" == "0" ];then
		license=$(uci get uswc.@uswc[0].license)
	else
		license="null"
	fi
	
	if [ "$license" != "$actlicense" ];then
		if [ "$license" = "null" ];then
			/usr/bin/uswc-service stop
			/usr/bin/uswc stop
		fi
		echo "Found New License: $license. Expiry time: $endtime"
		__ifupuswc1
		ps|grep frpc|grep -v grep
		if [ "$?" = "0" ];then
			'/tmp/frpc_'$ARCH reload -c /tmp/frpc.ini > /dev/null 2>&1 &
		fi
		if [ "$nodenum" = "2" ];then
			__ifupuswc2
		fi
	else
		echo "Pass! License: $license. Expiry time: $endtime"
	fi
}

update(){
        echo "###############################################################"
        echo "Check New version..."
		_checkinternet
		__getlicense
		_checkcdn
        versionurl=$(echo $cdn'md5')
        ipk=$(curl -C - --connect-timeout 3 -s $versionurl|grep uswc|tail -1|awk '{print $2}')
		upversion=$(echo $ipk|awk -F "_" '{print $2}')
        echo "The NEW VERSION is $upversion"
        read -r -p "Do you confirm the upgrade? [Y/n]" input
        case $input in
                [yY][eE][sS]|[yY])
						_installnewuswc
                        echo "Upgrade is complete. The current version is $upversion"
                        ;;

                [nN][oO]|[nN])
						version=$(uci get uswc.@uswc[0].version)
                        echo "Upgrade has been cancelled. The current version is $version"
                                ;;

                *)
                echo "Invalid input..."
                exit 1
                ;;
        esac
}

__resolvenodeip(){
	wandevice=$(uci get uswc.@uswc[0].gwdev)
	nodeip=$(curl -C - --connect-timeout 3 -s --interface $wandevice http://119.29.29.29/d?dn=$1.|awk -F ";" '{print $1}')
	__check_ip $nodeip
	if [ "$?" = "0" ];then
		echo $nodeip
	else
		nodeip=$(curl -C - --connect-timeout 3 -s --interface $wandevice http://182.254.116.116/d?dn=$1.|awk -F ";" '{print $1}')
		__check_ip $nodeip
		if [ "$?" = "0" ];then
			echo $nodeip
		else
			nodeip=$(curl -C - --connect-timeout 3 -s --interface $wandevice http://13.112.34.63/dn/?dn=$1|awk -F ";" '{print $1}')
			__check_ip $nodeip
			if [ "$?" = "0" ];then
				echo $nodeip
			else
				return 1
			fi
		fi
	fi
}

__check_ip(){
    echo $1|grep "^[0-9]\{1,3\}\.\([0-9]\{1,3\}\.\)\{2\}[0-9]\{1,3\}$" > /dev/null
    if [ "$?" = "0" ];then
        FIELD1=$(echo $1|cut -d. -f1)
        FIELD2=$(echo $1|cut -d. -f2)
        FIELD3=$(echo $1|cut -d. -f3)
        FIELD4=$(echo $1|cut -d. -f4)
        if [ "$FIELD1" -le "255" ] && [ "$FIELD2" -le "255" ] && [ "$FIELD3" -le "255" ] && [ "$FIELD4" -le "255" ]; then
            return 0
        else
            return 1
        fi
    else
        return 1
    fi
}

_change_mtu(){
	echo "###############################################################"
	echo "change mtu from script openconnect.sh..."
	grep "\-\-mtu" /lib/netifd/proto/openconnect.sh  > /dev/null 2>&1
	if [ "$?" != "0" ];then
		sed -i 's/--non-inter/--mtu=1399 &/' /lib/netifd/proto/openconnect.sh
	else
		echo "Pass!"
	fi
}

_checkcdn(){
	cdn=$(echo http://api.wsdwan.net/downloads/)
	#wandevice=$(uci get uswc.@uswc[0].gwdev)
	#cdninfo=$(curl --connect-timeout 3 -s cdn-cloudflare.uswc.net/state.html)
	#if [ "$cdninfo" = "200" ];then
	#	cdn=$(echo http://cdn-cloudflare.uswc.net/)
	#else
	#	cdn=$(echo http://api.wsdwan.net/downloads/)
	#fi
}