#!/bin/sh
_checkpid(){
	pid=`echo $$`
	pname=`echo $0`
	mypidfile=/tmp/myvpnd.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(){
	touch /etc/config/myvpn
	uci get  myvpn.@myvpn[0] > /dev/null 2>&1
	if [ "$?" != "0" ];then
		uci add myvpn myvpn
		uci set myvpn.@myvpn[0].version=`opkg list|grep luci-app-myvpnconfig|awk '{print $3}'`
		uci set myvpn.@myvpn[0].server=node.vps000.org
		uci commit myvpn
	fi
	echo "127.0.0.1 localhost">/etc/hosts
	echo "nameserver 180.76.76.76" > /etc/resolv.conf
	echo "nameserver 223.5.5.5" >> /etc/resolv.conf
}

_update(){
	newversion=`curl -s -k --connect-timeout 3 https://$apiserver/version|awk '{print $1}'`
	localversion=`uci get myvpn.@myvpn[0].version`
	if [ "$newversion" != "$localversion" ];then
		curl -s -k --connect-timeout 3 'https://'$apiserver'/downloads/ipk/luci-app-myvpnconfig_'$newversion'_all.ipk' > /tmp/'luci-app-myvpnconfig_'$newversion'_all.ipk'
		localipkmd5=`md5sum /tmp/'luci-app-myvpnconfig_'$newversion'_all.ipk'|awk '{print $1}'`
		newipkmd5=`curl -s -k --connect-timeout 3 https://$apiserver/version|awk '{print $2}'`
		if [ "$localipkmd5" = "$newipkmd5" ];then
			opkg install /tmp/'luci-app-myvpnconfig_'$newversion'_all.ipk'
			if [ "$?" = "0" ];then
				uci set myvpn.@myvpn[0].version=$newversion
				uci commit myvpn
				/etc/init.d/myvpn restart
			fi
		fi
	fi
}

_checkfile(){
	echo 0 > /tmp/myvpn_checkfile
	curl -s -k --connect-timeout 3 'https://'$apiserver'/'
}

_checkvpn(){
	myvpnpid=`cat /tmp/myvpn.pid`
	comm=`cat /proc/$myvpnpid/comm`
	if [ "$comm" != "myvpn" ];then
		echo run myvpn...
		/usr/sbin/myvpn start &
	else
		echo vpn is running!!
	fi
}

_restart_vpn(){
	echo restart myvpn
	myvpnpid=`cat /tmp/myvpn.pid`
	comm=`cat /proc/$myvpnpid/comm`
	if [ "$comm" = "myvpn" ];then
		kill -9 $myvpnpid
	fi
	/usr/sbin/myvpn start &
	echo my pid `cat /tmp/myvpn.pid`
}

_start(){
	_checkpid
	_init
	while true;do
		_update
		_checkfile
		_checkvpn
		sleep 10
	done
}

_start


