#!/bin/sh
. /lib/functions/network.sh
vpname=vps000
_checkpid(){
	pid=`echo $$`
	pname=`echo $0`
	mypidfile=/tmp/myvpn.pid
	if test -f "$mypidfile";then
		expid=`cat $mypidfile`
		if grep $pname /proc/`cat $mypidfile`/cmdline > /dev/null 2>&1 ;then
			echo "The process $pname is already exists ! pid:$expid."
			exit 0
		fi		
	fi
	echo $pid > $mypidfile
}

_init(){
	#删除之前的连接信息。确保使用最新用户信息创建连接
	ip link del vpn-$vpname > /dev/null 2>&1
	uci del network.$vpname > /dev/null 2>&1
	uci commit network
	
	#保持hosts干净防止本地劫持
	echo "127.0.0.1 localhost">/etc/hosts
	
	#检测myvpn配置文件
	touch /etc/config/myvpn
	uci get  myvpn.@myvpn[0] > /dev/null 2>&1
	if [ "$?" != "0" ];then
		 uci add myvpn myvpn
		 uci add_list myvpn.@myvpn[0].subnets="192.168.0.0/16"
		 uci add_list myvpn.@myvpn[0].subnets="100.64.0.0/12"
		 uci add_list myvpn.@myvpn[0].subnets="172.16.0.0/10"
		 uci add_list myvpn.@myvpn[0].subnets="10.0.0.0/8"
		 uci commit myvpn
	fi
	
	#临时设置DNS为180.76.76.76 防止本地DNS失效无法正常访问互联网
	echo "server=180.76.76.76" > /etc/dnsmasq.conf
	/etc/init.d/dnsmasq restart > /dev/null 2>&1
	
	#设置路由表，国内路由走本地互联网网关出口
	network_find_wan NET_IF
	network_get_gateway NET_GATEWAY "${NET_IF}"
	routenum=`ip route|grep $NET_GATEWAY|wc -l`
	if [ "$routenum" -lt "5000" ];then
		sed 's/^/ip route &/g' /etc/chnroute > /etc/quagga/zebra.conf
		sed -i "s/$/& $NET_GATEWAY/g" /etc/quagga/zebra.conf
		echo "" >> /etc/quagga/zebra.conf
		/etc/init.d/quagga restart > /dev/null 2>&1
	fi
	#修复wifi不在bridge中的问题。
	_fixbrwifi
}

_fixbrwifi(){
	cat /var/state/wireless >/dev/null 2>&1
	if [ "$?" = "0" ];then
		wifiuci=`cat /var/state/wireless | awk -F"." '{print $2}'`
		wififace=`uci get wireless.$wifiuci.ifname`
		brname=`brctl show|grep -v "bridge name"| awk '{print $1}'|grep -v $wififace`
		brctl show |grep $wififace > /dev/null 2>&1
		if [ "$?" != "0" ];then
			brctl addif $brname $wififace
		fi
	fi
}

_checkmyvpn(){
	if uci get myvpn.@myvpn[0].enable >/dev/null 2>&1;then
		_checkvpnconnect
	else
		ip link del vpn-$vpname > /dev/null 2>&1
		uci del network.$vpname > /dev/null 2>&1
		uci commit network
	fi
}

_checkvpnconnect(){
	if ifconfig vpn-$vpname >/dev/null 2>&1;then
		echo vpn-$vpname already exists!
	else
		_connectvpn
	fi
}

_connectvpn(){
	ip link del vpn-$vpname > /dev/null 2>&1
	uci del network.$vpname > /dev/null 2>&1
	uci commit network
	apiserver=`uci get myvpn.@myvpn[0].server|sed s/[[:space:]]//g`
	api_info=`curl -s -k -A openwrt https://$apiserver/openwrt/api.php`
	. /usr/share/libubox/jshn.sh
	json_load $api_info
	json_get_var status status
	if [ "$status" = "200" ];then
		json_get_var vpnserver vpnserver
		echo $vpnserver
		json_get_var vpnport vpnport
		echo $vpnport
	else
		exit
	fi
	
	vpnusername=`uci get myvpn.@myvpn[0].username|sed s/[[:space:]]//g`
	vpnpassword=`uci get myvpn.@myvpn[0].password|sed s/[[:space:]]//g`
	#这里需要添加一个vpn账号密码检测。如果用户名密码错误或到期就提示用户。正确了再正常添加VPN连接。
	uci set network.$vpname=interface
	uci set network.$vpname.proto='openconnect'
	uci set network.$vpname.auto='0'
	uci set network.$vpname.delegate='0'
	uci set network.$vpname.defaultroute='0'
	uci set network.$vpname.port=$vpnport
	uci set network.$vpname.username=$vpnusername
	uci set network.$vpname.password=$vpnpassword
	uci set network.$vpname.server=$vpnserver
	uci commit network.$vpname
	FIREWALL=$(uci get firewall.@zone[1].network)
	echo $FIREWALL|grep $vpname >/dev/null
	if [ "$?" != "0" ];then
		echo " Add $vpname to Firewall"
		uci set firewall.@zone[1].network="$FIREWALL $vpname"
		uci commit firewall
	fi
	ifup $vpname
	ip route add 0.0.0.0/1 dev vpn-$vpname
	ip route add 128.0.0.0/1 dev vpn-$vpname
	#连接成功后设置dns为智能解析。
	_checkdnsmasq
}

_checkdnsmasq(){
cat>/etc/dnsmasq.conf<<EOF
no-resolv
all-servers
server=180.76.76.76,0
server=114.114.114.114,0
server=1.1.1.1,1
server=8.8.8.8,1
chnroutes-file=/etc/chnroute

EOF
	/etc/init.d/dnsmasq restart > /dev/null 2>&1
}

_upgrade(){
	new_version=`curl -s -k --connect-timeout 3 https://$apiserver/downloads/ipk/md5|tail -1|awk '{print $2}'|awk -F "_" '{print $2}'`
	if [ "${#new_version}" = "4" ];then
		version=`uci get myvpn.@myvpn[0].version`
		if [ "$new_version" != "$version" ];then
			new_info=`curl -L -s -k --connect-timeout 3 https://$apiserver/downloads/ipk/md5|tail -1`
			new_md5=`echo $new_info|awk '{print $1}'`
			new_ipk=`echo $new_info|awk '{print $2}'`
			curl -L -s -k --connect-timeout 5 https://$apiserver/downloads/ipk/$new_ipk > /tmp/$new_ipk
			download_md5=`md5sum /tmp/$new_ipk|awk '{print $1}'`
			if [ "$new_md5" = "$download_md5" ];then
				opkg install /tmp/$new_ipk --force-depends
				if [ "$?" = "0" ];then
					uci set myvpn.@myvpn[0].version="$new_version"
					uci commit myvpn
				fi
				rm -rf /tmp/$new_ipk
			fi
		fi
	fi
}

_getwan(){
	. /lib/functions/network.sh
	network_find_wan NET_IF
	network_get_gateway NET_GATEWAY "${NET_IF}"
	echo $NET_GATEWAY
}

_start(){
	_checkpid
	_init
	while true;do
		_checkmyvpn
		_upgrade
	sleep 10
	done
}

_stop(){
	ip link del vpn-$vpname > /dev/null 2>&1
	uci del network.$vpname > /dev/null 2>&1
	uci commit network
	/etc/init.d/myvpn stop
}


action=$1
case "$action" in
stop) 
	_stop
	;;
upgrade) 
	_upgrade
	;;
getwan) 
	_getwan
	;;
*)
    _start
    ;;
esac

