# Typical Debian initscript, but as a library rather than copy-paste.
#
# Usage:
#   NAME=short-name
#   DESC="Textual description"
#   SCRIPTNAME=/etc/init.d/$NAME  # default if omitted
#   . /lib/init/std-init.sh
#   do_start() { ... }
#   do_stop() { ... }
#   do_reload() { ... }  # optional
#   std_init "$1"

. /lib/init/vars.sh
. /lib/lsb/init-functions

[ -r /etc/default/"$NAME" ] && . /etc/default/"$NAME"

SCRIPTNAME="${SCRIPTNAME:-/etc/init.d/$NAME}"

have_reload()
{
  type do_reload >/dev/null 2>/dev/null
}

usage_exit()
{
  if have_reload; then
    echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
  else
    echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
  fi
  exit 3
}

std_init()
{
  local cmd
  case "$1" in
    start|stop|restart)
      cmd="$1" ;;
    reload)
      if have_reload; then cmd=reload; else usage_exit; fi ;;
    force-reload)
      if have_reload; then cmd=reload; else cmd=restart; fi ;;
    *)
      usage_exit ;;
  esac
    
  case $cmd in
    start)
      [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
      do_start
      case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
      esac
      ;;
    stop)
      [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
      do_stop
      case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
      esac
      ;;
    reload)
      log_daemon_msg "Reloading $DESC" "$NAME"
      do_reload
      log_end_msg $?
      ;;
    restart)
      log_daemon_msg "Restarting $DESC" "$NAME"
      do_stop
      case "$?" in
        0|1)
          do_start
          case "$?" in
            0) log_end_msg 0 ;;
            1) log_end_msg 1 ;; # Old process is still running
            *) log_end_msg 1 ;; # Failed to start
          esac
          ;;
        *)
          # Failed to stop
          log_end_msg 1
          ;;
      esac
      ;;
  esac

  :
}
