#!/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"

test -x $DAEMON || exit 0
test -d /etc/cipe/peers || exit 0
if [ "x$(ls /etc/cipe/peers)" = "x" ]; then
    echo CIPE is not configured yet, stopping.
    exit 0
fi

set -e

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

function start_all () {
    for i in /etc/cipe/peers/*
    do
        echo -n "$(basename $i) "
        start-stop-daemon --start --quiet --exec $DAEMON \
            -- -o "$i"
    done
}

case "$1" in
  start)
        echo -n "Starting $DESC: "
        start_all
	echo "$NAME."
	;;
  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
