#!/bin/sh
#
# openl2tpd          Start/Stop the OpenL2TP protocol daemon.
#
# chkconfig: 2345 57 76
# description: OpenL2TP is a complete implementation of RFC2661 - Layer Two Tunneling
#	       Protocol Version 2, able to operate as both a server and a client.  It
#              can be used to implement L2TP VPNs. As a server, it can handle
#              hundreds of tunnels and sessions.
# processname: openl2tpd
# config: /etc/sysconfig/openl2tpd
# pidfile: /var/run/openl2tpd.pid

# Source function library.
. /etc/init.d/functions

OPENL2TPDARGS=""
OPENL2TPD_CONFIG_FILE=""

[ -f /etc/sysconfig/openl2tpd ] && . /etc/sysconfig/openl2tpd
 
start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/openl2tpd ]; then
		msg_already_running "openl2tpd"
		return
	fi
	
	msg_starting "openl2tpd"
	emit starting JOB=openl2tpd
	
	modprobe -s pppol2tp || modprobe -s l2tp_ppp
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
	    daemon openl2tpd $OPENL2TPDARGS
	    RETVAL=$?
	fi
	if [ $RETVAL -eq 0 ]; then
	    touch /var/lock/subsys/openl2tpd
	    emit started JOB=openl2tpd
	    if [ -n "$OPENL2TPD_CONFIG_FILE" -a -f "$OPENL2TPD_CONFIG_FILE" ]; then
		sleep 1
		show "Restoring saved openl2tpd configuration..." ; busy
		/usr/bin/l2tpconfig config restore file="$OPENL2TPD_CONFIG_FILE"
		RETVAL=$?
		if [ $RETVAL -eq 0 ] ; then
			ok
		else
			fail
		fi
	    fi
	fi
}

stop() {
	if [ ! -f /var/lock/subsys/openl2tpd ]; then
		msg_not_running "openl2tpd"
		return
	fi
	msg_stopping "openl2tpd"
	killproc openl2tpd
	emit --no-wait stopped JOB=openl2tpd
	rm -f /var/run/openl2tpd.pid /var/lock/subsys/openl2tpd >/dev/null 2>&1
	return 0
}	

condrestart() {
	if [ ! -f /var/lock/subsys/openl2tpd ]; then
		msg_not_running "openl2tpd"
		RETVAL=$1
		return
	fi

  	stop
	start
}	

restart() {
  	stop
	start
}	

reload() {
	if [ ! -f /var/lock/subsys/openl2tpd ]; then
		msg_not_running "openl2tpd"
		RETVAL=7
		return
	fi

	if [ -n "$OPENL2TPD_CONFIG_FILE" -a -f "$OPENL2TPD_CONFIG_FILE" ]; then
		msg_reloading "openl2tpd"
		/usr/bin/l2tpconfig config restore file="$OPENL2TPD_CONFIG_FILE"
		RETVAL=$?
		if [ $RETVAL -eq 0 ] ; then
			ok
		else
			fail
		fi
	else
		stop
		start
	fi
}	

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
  	restart
	;;
  try-restart)
	condrestart 0
	;;
  reload|force-reload)
  	reload
	;;
  status)
  	status openl2tpd
	RETVAL=$?
	l2tpconfig system show status
	;;
  condrestart)
	condrestart
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|reload|force-reload|status}"
	exit 3
esac

exit $RETVAL

