#!/bin/sh
#
# openvpn	Start/stop the VPN daemon.
#
# chkconfig:	2345 80 20
#
# description:	OpenVPN is a robust and highly configurable VPN (Virtual
#		Private Network) daemon
#

# Source function library
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network ]; then
		msg_network_down OpenVPN
		exit 1
	fi
else
	exit 0
fi

# Get service config
[ -f /etc/sysconfig/openvpn ] && . /etc/sysconfig/openvpn


# See how we were called.
case "$1" in
  start)
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/openvpn ]; then
		msg_starting "OpenVPN" ; started
		if [ -z "$TUNNELS" ]; then
			nls "No tunnels configured in /etc/sysconfig/openvpn"
			exit 6
		fi
		for tun in $TUNNELS ; do
			show "Starting OpenVPN tunnel %s" "$tun"
			daemon openvpn --daemon --writepid "/var/run/openvpn/$tun.pid" \
				--config "/etc/openvpn/$tun.conf" --cd /etc/openvpn
			RET=$?
			[ $RETVAL -eq 0 ] && RETVAL=$RET
		done
		[ $RETVAL -eq 0 ] && touch /var/lock/subsys/openvpn
	else
		msg_already_running "OpenVPN"
	fi
	;;
  stop)
	if [ -f /var/lock/subsys/openvpn ]; then
		# Stop daemons.
		msg_stopping "OpenVPN"; started
		for pidfile in /var/run/openvpn/*.pid ; do
			[ -f "$pidfile" ] || continue
			pid=`cat "$pidfile"`
			tun=`basename "$pidfile" | sed -e 's/\.pid$//'`
			show "Stopping OpenVPN tunnel %s" "$tun" ; busy
			if ! ps h $pid >/dev/null 2>&1 ; then
				died
				continue
			fi
			kill -TERM $pid >/dev/null 2>&1 
			usleep 100000
			if ps h $pid >/dev/null 2>&1 ; then
				sleep 1
				if ps h $pid >/dev/null 2>&1 ; then
					sleep 3
					if ps h $pid >/dev/null 2>&1 ; then
						kill -KILL $pid >/dev/null 2>&1
					fi
				fi
			fi
			ok
		done
		rm -f /var/lock/subsys/openvpn >/dev/null 2>&1
	else
		msg_not_running "OpenVPN"
	fi
	;;
  status)
	status openvpn
	exit $?
	;;
  reload|force-reload)
	if [ -f /var/lock/subsys/openvpn ]; then
		msg_reloading "OpenVPN"
		busy
		for pid in /var/run/openvpn/*.pid ; do
			kill -HUP $pid
			[ $? -ne 0 -a $RETVAL -eq 0 ] && RETVAL=7
		done
		[ $RETVAL -eq 0 ] && ok || died
        else
                msg_not_running OpenSSH >&2
                exit 7
	fi 		
	;;
  restart)
	$0 stop
	sleep 1
	$0 start
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|force-reload|status}"
	exit 3
esac

exit $RETVAL
