#! /bin/sh
#
# chkconfig:	345 60 40
# description:	Virtual Private Network (VPN) daemon that uses \
# 		tunnelling and encryption to create a secure private \
#		network between hosts on the Internet.
# processname:	tincd
# config:	/etc/sysconfig/tinc
### BEGIN INIT INFO
# Provides: tinc
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: Virtual Private Network (VPN) daemon
# Description:	Virtual Private Network (VPN) daemon that uses
# 		tunnelling and encryption to create a secure private
#		network between hosts on the Internet.
### END INIT INFO
WITHOUT_RC_COMPAT=1

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

unset TINC_ARGS

# For multiple TINC instances:
# - make symlinks with names tinc-TUN
# - create configuration in /etc/sysconfig/tinc-TUN
#   with proper tunnel name in TINC_ARGS
TUN_NAME=`/bin/basename $0 | /bin/sed -e 's/^[SK][0-9]\+//'`

# Get config
SourceIfNotEmpty /etc/sysconfig/network
SourceIfNotEmpty /etc/sysconfig/$TUN_NAME

LOCKFILE=/var/lock/subsys/$TUN_NAME
RETVAL=0

PIDFILE=`echo "$TINC_ARGS" |  sed -ne 's/.*--pidfile=\([^ ]\+\).*/\1/ p'`
if [ -z "$PIDFILE" ]; then
    VPNNAME=`echo "$TINC_ARGS" |  sed -ne 's/.*-n \([^ ]\+\).*/\1/ p'`
    if [ -n "$VPNNAME" ]; then
        PIDFILE="/var/run/tinc.$VPNNAME.pid"
    else
        PIDFILE="/var/run/tinc.pid"
    fi
fi

start()
{
	msg_starting $"TINC"
	start_daemon --lockfile "$LOCKFILE" --pidfile "$PIDFILE" -- tincd "$TINC_ARGS"
	RETVAL=$?
	return $RETVAL
}

stop()
{
	msg_stopping $"TINC"
	stop_daemon --lockfile "$LOCKFILE" --pidfile "$PIDFILE" -- tincd
	RETVAL=$?
	return $RETVAL
}

restart()
{
	stop
	start
}

reload()
{
	msg_reloading $"TINC"
	stop_daemon --lockfile "$LOCKFILE" --pidfile "$PIDFILE" --expect-user root -HUP -- tincd
	RETVAL=$?
	return $RETVAL
}
	

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status --pidfile "$PIDFILE" -- tincd
		RETVAL=$?
		;;
	restart)
		restart
		;;
	reload|force-reload)
		reload
		;;

	condstop)
		if [ -f "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart|try-restart)
		if [ -f "$LOCKFILE" ]; then
			restart
		fi
		;;
	*)
		msg_usage "${0##*/} {start|stop|status|restart|try-restart|reload|force-reload|condstop|condrestart}"
		RETVAL=1
esac

exit $RETVAL
