#!/sbin/runscript

# OpenVPN start/stop script
# Adapted to Gentoo by James Yonan

# Originally Contributed to the OpenVPN project by
# Douglas Keller <doug@voidstar.dyndns.org>
# 2002.05.15

# This script does the following:
#
# - Starts an openvpn process for each .conf file it finds in
#   /etc/openvpn.
#
# - If /etc/openvpn/xxx.sh exists for a xxx.conf file then it executes
#   it before starting openvpn (useful for doing openvpn --mktun...).

# - In addition to start/stop you can do:
#
#   service openvpn reload - SIGHUP
#   service openvpn reopen - SIGUSR1
#   service openvpn status - SIGUSR2

# Location of openvpn binary
openvpn=/usr/local/sbin/openvpn

# PID directory
piddir=/var/run/openvpn

# Our working directory (.conf files should be here)
work=/etc/openvpn

# Our options
opts="start stop restart condrestart"

depend() {
    need net
    use dns
}

start() {
    ebegin "Starting OpenVPN"

    # Load the TUN/TAP module
    /sbin/modprobe tun >/dev/null 2>&1

    if [ ! -d  $piddir ]; then
	mkdir $piddir
    fi

    cd $work

    # Start every .conf in $work and run .sh if exists
    local errors=0
    local successes=0
    local retstatus=0
    for c in `/bin/ls *.conf 2>/dev/null`; do
	bn=${c%%.conf}
	if [ -f "$bn.sh" ]; then
	    . $bn.sh
	fi
	rm -f $piddir/$bn.pid
	$openvpn --daemon openvpn-$bn --writepid $piddir/$bn.pid --config $c --cd $work
	if [ $? = 0 ]; then
	    successes=1
	else
	    errors=1
	fi
    done

    # Decide status based on errors/successes.
    # If at least one tunnel succeeded, we return success.
    # If some tunnels succeeded and some failed, we return
    #   success but give a warning.
    if [ $successes = 1 ]; then
	if [ $errors = 1 ]; then
	    ewarn "Note: At least one OpenVPN tunnel failed to start"
	fi
    else
	retstatus=1
	if [ $errors = 0 ]; then
	    ewarn "Note: No OpenVPN configuration files were found in $work"
	fi
    fi
    eend $retstatus "Error starting OpenVPN"
}

stop() {
    ebegin "Stopping OpenVPN"
    for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
	if [ -s $pidf ]; then
	    kill `cat $pidf` >/dev/null 2>&1
	fi
	rm -f $pidf
    done
    eend 0
}

# this should really be in runscript.sh
started() {
    if [ -L "${svcdir}/started/${myservice}" ]; then
	return 1
    else
	return 0
    fi
}

# attempt to restart ONLY if we are already started
condrestart() {
    started || restart
}
