#!/bin/sh

DESC=jolicloud-tunnel

DAEMON_PID=/var/run/$DESC.pid
CONFIG_DIR=/usr/lib/$DESC
STATUS_FILE=/var/run/$DESC.status
LOG_FILE=/var/log/$DESC.log

DAEMON=/usr/sbin/openvpn
DAEMON_ARG="--daemon $DESC --writepid $DAEMON_PID --cd $CONFIG_DIR --log-append $LOG_FILE"
STATUS_ARG="--status $STATUS_FILE 10"
CONFIG_ARG="--config /usr/lib/$DESC/openvpn.conf"
AUTOSTART=0

. /lib/lsb/init-functions

if test -e /etc/default/jolicloud-tunnel; then
    . /etc/default/jolicloud-tunnel
fi

case "$1" in
    start)
        log_action_begin_msg "Starting $DESC"
        STATUS=0
        if test -e $DAEMON_PID; then
            if ps fax | grep -q ^`cat $DAEMON_PID`; then
                log_warning_msg "  Already running."
            else
                rm $DAEMON_PID
            fi
        fi
        if test -z "$AUTOSTART" -o "$AUTOSTART" = "0"; then
            log_warning_msg "  Autostart disabled, no tunnel will be started."
            exit 0
        fi
        if test ! -e $DAEMON_PID; then
            $DAEMON $DAEMON_ARG $STATUS_ARG $CONFIG_ARG < /dev/null || STATUS=1
        fi
        log_end_msg $STATUS
        ;;

    stop)
        log_action_begin_msg "Stopping $DESC";
        if test -e $DAEMON_PID; then
            kill `cat $DAEMON_PID` || true
            rm -f $DAEMON_PID
            rm -f $STATUS_FILE 2> /dev/null
        else
            log_warning_msg "  No VPN is running."
        fi
        log_end_msg 0
        ;;
    *)
        echo "Usage $0 {start|stop|reload|restart|force-reload|cond-restart|status}"
        exit 1
        ;;
esac

exit 0
