#!/bin/sh
#
# cipe		Start/stop the CIPE daemon
#
#		Written by Tommi Virtanen <tv@debian.org>
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/ciped
NAME=ciped
DESC="encrypted tunnel"

PEERDIR=/etc/cipe/peers
test -x $DAEMON || exit 0
test -d $PEERDIR || exit 0

PEERS=$(ls $PEERDIR | grep -v '~$')
if [ "x$PEERS" = "x" ]; then
    echo CIPE is not configured yet, stopping.
    exit 0
fi

set -e

stop_all () {
    for interface in $(/sbin/ifconfig|grep ^cip|sed 's/ .*//g'); do
        /sbin/ifconfig "$interface" down
    done
}

start_all () {
    for peer in $PEERS
    do
        echo -n "$peer "
        start-stop-daemon --start --quiet --exec $DAEMON \
            -- -o "$PEERDIR/$peer"
    done
}

case "$1" in
  start)
        echo -n "Starting $DESC: "
        start_all
	echo "$NAME."
	;;
  maybe-start)
        if [ "$2" = "$(uname -r)" ]; then
            echo -n "Starting $DESC: "
            start_all
            echo "$NAME."
        fi
	;;
  stop)
	echo -n "Stopping $DESC: "
        stop_all
	echo "$NAME."
	;;
  maybe-stop)
        if [ "$2" = "$(uname -r)" ]; then
            echo -n "Stopping $DESC: "
            stop_all
            echo "$NAME."
        fi
	;;
  restart|force-reload)
	echo -n "Restarting $DESC: "
        stop_all
	sleep 1
	start_all
	echo "$NAME."
	;;
  *)
	N=/etc/init.d/cipe
	echo "Usage: $N {start|stop|restart|force-reload|maybe-stop kvers}" >&2
	exit 1
	;;
esac

exit 0
