#!/bin/sh
### BEGIN INIT INFO
# Provides:          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

DAEMON=/usr/sbin/openvpn
CONFIG_DIR=/etc/openvpn/server
RUN_DIR=/var/run/openvpn-server
LOGFILE=/var/log/openvpn/openvpn.log

case "$1" in
    start)
        test -x "$DAEMON"
        mkdir -p "$RUN_DIR" /var/log/openvpn
        touch "$LOGFILE"
        for config in "$CONFIG_DIR"/*.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
                continue
            fi
            rm -f "$pidfile"
            "$DAEMON" --daemon "mlu-openvpn-server-$name" \
                --config "$config" --writepid "$pidfile" \
                --log-append "$LOGFILE" \
                --status "$RUN_DIR/$name.status" --status-version 2
        done
        ;;
    stop)
        for pidfile in "$RUN_DIR"/*.pid; do
            test -f "$pidfile" || continue
            start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
                --pidfile "$pidfile" || true
            rm -f "$pidfile"
        done
        ;;
    reload|force-reload)
        for pidfile in "$RUN_DIR"/*.pid; do
            test -f "$pidfile" || continue
            kill -HUP `cat "$pidfile"` 2>/dev/null || true
        done
        ;;
    restart)
        "$0" stop
        "$0" start
        ;;
    status)
        status=3
        for pidfile in "$RUN_DIR"/*.pid; do
            test -f "$pidfile" || continue
            status=0
            kill -0 `cat "$pidfile"` 2>/dev/null || status=3
        done
        exit "$status"
        ;;
    *)
        echo "Usage: $0 {start|stop|reload|force-reload|restart|status}" >&2
        exit 1
        ;;
esac

exit 0
