#!/bin/sh
#
# pkcipe    Start/stop the PKCIPE daemon
#
#    Written by Agthorr <agthorr@barsoom.org>
#    Based heavily on the cipe-common script by Tommi Virtanen <tv@debian.org>
#    Fixed here and there by Sam Hocevar <sam@zoy.org>
#

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

PKDIR="/etc/cipe/pk"
test -x "$DAEMON" || exit 0
test -d "$PKDIR" || exit 0

PKS=$(find "$PKDIR" -type f -maxdepth 1 '!' -name '*~' -exec basename '{}' ';')
if [ "x$PKS" = "x" ]; then
    echo No pkcipe tunnels configured yet, stopping.
    exit 0
fi

stop_all () {
  for pk in $PKS; do
    IPADDR=`awk '{ if($1=="ipaddr") print $2 }' "$PKDIR/$pk"`
    PTPADDR=`awk '{ if($1=="ptpaddr") print $2 }' "$PKDIR/$pk"`
    if test -n "$IPADDR" -a -n "$PTPADDR"; then
      INTERFACE=`ifconfig | grep -A1 '^cip' | fgrep -B1 'inet addr:'$IPADDR | fgrep -B1 'P-t-P:'$PTPADDR | sed -e 's/ .*//' -eq`
      if test -n "$INTERFACE"; then
        echo -n "$pk "
        ifconfig "$INTERFACE" down
      fi
    fi
  done
}

start_all () {
  for pk in $PKS; do
    echo -n "$pk "
    start-stop-daemon --start --quiet --exec $DAEMON -- -c "$pk:963"
  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
