#!/bin/sh
### BEGIN INIT INFO
# Provides:          mlu-openvpn-server
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Should-Start:      $named
# Should-Stop:       $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: OpenVPN server tunnels
### END INIT INFO

set -e

. /lib/lsb/init-functions

DAEMON=/usr/sbin/openvpn
CONFIG_DIR=/etc/openvpn/server
RUN_DIR=/var/run/openvpn-server
LOG_FILE=/var/log/openvpn/openvpn.log
STATUS_FILE=/var/log/openvpn/openvpn-status.log

start_instance()
{
	config="$1"
	name=`basename "$config" .conf`
	pidfile="$RUN_DIR/$name.pid"
	statusfile="$RUN_DIR/$name.status"
	if test "$name" = openvpn; then
		statusfile="$STATUS_FILE"
	fi

	if test -f "$pidfile" && kill -0 `cat "$pidfile"` 2>/dev/null; then
		return 0
	fi

	rm -f "$pidfile"
	"$DAEMON" --daemon "mlu-openvpn-server-$name" \
		--config "$config" --writepid "$pidfile" \
		--log-append "$LOG_FILE" --status "$statusfile" \
		--status-version 2
}

stop_instance()
{
	config="$1"
	name=`basename "$config" .conf`
	pidfile="$RUN_DIR/$name.pid"

	if test -f "$pidfile"; then
		start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
			--pidfile "$pidfile" || true
		rm -f "$pidfile"
	fi
}

reload_instance()
{
	config="$1"
	name=`basename "$config" .conf`
	pidfile="$RUN_DIR/$name.pid"

	if test -f "$pidfile"; then
		kill -HUP `cat "$pidfile"` 2>/dev/null || true
	fi
}

case "$1" in
	start)
		mkdir -p "$RUN_DIR"
		mkdir -p /var/log/openvpn
		touch "$LOG_FILE" "$STATUS_FILE"
		cd "$CONFIG_DIR"
		for config in *.conf; do
			test -f "$config" || continue
			start_instance "$CONFIG_DIR/$config"
		done
		;;
	stop)
		cd "$CONFIG_DIR"
		for config in *.conf; do
			test -f "$config" || continue
			stop_instance "$CONFIG_DIR/$config"
		done
		;;
	reload|force-reload)
		cd "$CONFIG_DIR"
		for config in *.conf; do
			test -f "$config" || continue
			reload_instance "$CONFIG_DIR/$config"
		done
		;;
	restart)
		"$0" stop
		"$0" start
		;;
	status)
		status=0
		cd "$CONFIG_DIR"
		for config in *.conf; do
			test -f "$config" || continue
			name=`basename "$config" .conf`
			pidfile="$RUN_DIR/$name.pid"
			if test -f "$pidfile" && kill -0 `cat "$pidfile"` 2>/dev/null; then
				echo "$name is running"
			else
				echo "$name is not running"
				status=3
			fi
		done
		exit "$status"
		;;
*)
		echo "Usage: $0 {start|stop|reload|force-reload|restart|status}" >&2
		exit 1
		;;
esac

exit 0
