#! /bin/sh

# --------------------------------------------------------------------------
# No user configurable parts below this line.
DIALD=/usr/sbin/diald
FIFO=""

#. /etc/init.d/functions

# Make sure that we don't get started if there is no options file.
# We certainly don't want to get started if diald is missing.
test -x /usr/sbin/diald || exit 0
test -f /etc/diald/diald.options || exit 0

# Look for fifo in config file
NEW_FIFO=`egrep '^[^#]*fifo' /etc/diald/diald.options | sed -e 's/^ *fifo *//'`
if [ "$NEW_FIFO" != "" ]; then
    # The user location exists, and is a named pipe.
    FIFO="$NEW_FIFO";
fi

case "$1" in
  start)
      echo -n "Starting on-demand dialing daemon: "
      if [ "$FIFO" != "" ] ; then
        if test -p $FIFO ; then
          rm -f $FIFO
        fi
        mknod --mode=0660 $FIFO p
        chown root.dialout $FIFO
	if test -p $FIFO ; then
          echo -n "fifo-created "
        fi
      fi
      start-stop-daemon --start --quiet \
              --pidfile /var/run/diald.pid --exec /usr/sbin/diald
      echo "diald."
    ;;
  stop)
      echo -n "Stopping on-demand dialing daemon: "
      if [ "$FIFO" != "" ] ; then
        if test -p $FIFO ; then
          rm -f $FIFO
          echo -n "fifo-removed "
        fi
      fi
      start-stop-daemon --stop --quiet \
              --pidfile /var/run/diald.pid --exec /usr/sbin/diald
      echo "diald."
    ;;
  reload)
      if [ "$FIFO" != "" ] ; then
        if test -p $FIFO ; then
	  echo "reset" > $FIFO
	  echo "Diald configuration reloaded."
	else
	  echo "Cannot reload diald configuration: $FIFO not found."
	  exit 2
        fi
      else
        echo "Cannot reload diald configuration: "
	echo "  need a fifo statement in /etc/diald/diald.options."
	exit 2
      fi
    ;;
  force-reload|restart)
      echo -n "Stopping diald... "
      pid=`cat /var/run/diald.pid`
      start-stop-daemon --stop --quiet --pidfile /var/run/diald.pid \
	--exec /usr/sbin/diald
      while ps $pid >/dev/null 2>/dev/null
      do
	echo -n "waiting... "
	sleep 5
      done
      echo "done."
      start-stop-daemon --start --quiet \
              --pidfile /var/run/diald.pid --exec /usr/sbin/diald
      echo "Diald restarted."
    ;;
  *)
      echo "Usage: /etc/init.d/diald {start|stop|reload|restart|force-reload}"
      exit 1
    ;;
esac

exit 0

