#! /bin/sh
# $Id: miredo.init 1775 2006-10-05 15:04:18Z remi $
#
# miredo start/stop script for Debian GNU/Linux
# Author: Rémi Denis-Courmont <rdenis (at) simphalempin (dot) com>
#
# chkconfig: 345 17 83
# description: Starts and stops the Miredo daemon \
#	       used to provide IPv6 tunneling over UDP through NAT.
#
### BEGIN INIT INFO
# Provides:          
# Required-Start:    $local_fs $remote_fs $network $syslog $time
# Required-Stop:     $local_fs $remote_fs $syslog
# Short-Description: Teredo IPv6 tunnel
# Description:       Miredo daemon for tunneling of IPv6 through NAT
#                    within UDP/IPv4, as specified by the Teredo mechanism.
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
### END INIT INFO


PATH=/usr/sbin:/usr/bin:/sbin:/bin
DESC="Teredo IPv6 tunneling daemon"
NAME=miredo
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS=""
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
CHECKCONF="${DAEMON}-checkconf"

[ -x "$DAEMON" ] || exit 0

# Source defaults.
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Ensure configuration is readable.
[ -r /etc/$NAME.conf ] || exit 0

. /lib/lsb/init-functions

check_start() {
	if [ "x$START_MIREDO" != "xtrue" ]; then
		echo "START_MIREDO is set to false in /etc/default/$NAME."
		echo "$DAEMON not starting."
		exit 0
	fi
	if [ ! -e /dev/net/tun ]; then
		echo "/dev/net/tun does not exist."
		echo "$DAEMON cannot be started."
		exit 0
	fi
}

check_conf_file() {
	# FIXME: should use DAEMON_ARGS as set when the daemon was started
	if ! "$CHECKCONF" $DAEMON_ARGS; then
		echo "Cannot reload miredo: fix /etc/$NAME.conf first."
		exit 1
	fi
}

check_chroot_dir() {
	if [ -d "/var/run/$NAME" ]; then
		mkdir -p "/var/run/$NAME"
		chmod 0755 "/var/run/$NAME"
	fi
}


case "$1" in
  start)
	check_start
	check_chroot_dir
	log_daemon_msg "Starting $DESC" "$NAME"
	start-stop-daemon --start --quiet --pidfile "$PIDFILE" \
		--exec "$DAEMON" --oknodo -- $DAEMON_ARGS
	log_end_msg $?
	;;
  stop)
	log_daemon_msg "Stopping $DESC" "$NAME"
	start-stop-daemon --stop --quiet --pidfile "$PIDFILE" \
		--retry 1 --oknodo
	log_end_msg $?
	;;
  reload|force-reload)
	check_conf_file
	log_daemon_msg "Reloading $DESC" "$NAME"
	start-stop-daemon --stop --signal 1 --quiet --pidfile "$PIDFILE" \
		--exec "$DAEMON"
	log_end_msg $?
	;;
  restart)
	check_start # avoid stopping if would not restart
	check_conf_file
	$0 stop
	sleep 1
	$0 start
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
	exit 1
	;;
esac

exit $?

