#!/bin/sh
# chkconfig: 345 77 15
# description: Plesk VPN

SERVICE_NAME="psa-vpn"
MODULE="vpn"
PRODUCT_ROOT_D="/usr/local/psa"

action="$1"
conf="$PRODUCT_ROOT_D/var/modules/$MODULE/openvpn.conf"
pid="$PRODUCT_ROOT_D/var/modules/$MODULE/openvpn.pid"

case "$action" in

	start)
		if [ -f "$conf" ]; then
			if [ -f "$pid" ]; then
				pid_value=`cat "$pid"`
				echo "$SERVICE_NAME: OpenVPN is already running with pid $pid_value"
				exit 0
			else
				if $PRODUCT_ROOT_D/admin/sbin/modules/$MODULE/openvpn --config "$conf"; then
					echo "$SERVICE_NAME: OpenVPN has been started"
					exit 0
				else
					echo "$SERVICE_NAME: OpenVPN failed to start"
					exit 1
				fi
			fi
		elif [ -f "$pid" ]; then
			echo "$SERVICE_NAME: OpenVPN is disabled, stopping"
			"$0" stop
			exit
		else
			echo "$SERVICE_NAME: OpenVPN is disabled"
			exit 0
		fi
		;;

	stop)
		if [ -f "$pid" ]; then
			kill `cat "$pid"`
			rm -f "$pid"
			echo "$SERVICE_NAME: OpenVPN has been stopped"
			exit 0
		else
			echo "$SERVICE_NAME: No OpenVPN found running"
			exit 0
		fi
		;;

	restart)
		if [ -f "$pid" ]; then
			"$0" stop
		fi
		"$0" start
		exit
		;;

	reconfigure|reload|force-reload)
		if [ ! -f "$conf" ]; then
			echo "$SERVICE_NAME: OpenVPN is disabled, stopping"
			"$0" stop
			exit
		elif [ -f "$pid" ]; then
			kill -HUP `cat "$pid"`
			echo "$SERVICE_NAME: Sent a signal to OpenVPN to reread the configuration file"
			exit
		else
			"$0" start
			exit
		fi
		;;

	rekey)
		if [ ! -f "$conf" ]; then
			echo "$SERVICE_NAME: OpenVPN is disabled, stopping"
			"$0" stop
			exit
		elif [ -f "$pid" ]; then
			kill -USR1 `cat "$pid"`
			echo "$SERVICE_NAME: Sent a signal to OpenVPN to reread the key file"
			exit
		else
			"$0" start
			exit
		fi
		;;

	status)
		if [ -f "$pid" ]; then
			pid_value=`cat "$pid"`
			echo "OpenVPN is running with pid $pid_value"
			exit 0
		else
			echo "OpenVPN is stopped"
			exit 1
		fi
		;;

	help)
		echo "usage: $0 <arg>"
		echo "where argument is one from the list:"
		cat << EOF
	start       -- start ${SERVICE_NAME}
	stop        -- stop ${SERVICE_NAME}
	restart     -- restart ${SERVICE_NAME} if running or start if not running
	reconfigure -- make ${SERVICE_NAME} re-read the configuration file if running or start if not running
	rekey       -- make ${SERVICE_NAME} re-read the authentication key if running or start if not running
	status      -- show ${SERVICE_NAME} status
	help        -- this screen

EOF
		exit 1
		;;

	*)
		echo "usage: $0 (start|stop|restart|reconfigure|rekey|status|help)"
		exit 1
		;;
esac
