#!/bin/bash
#
# apache-perl	Start the apache-perl HTTP server.
#
# The variables below are NOT to be changed.  They are there to make the
# script more readable.

set -e

. /lib/lsb/init-functions

NAME=apache-perl
DAEMON=/usr/sbin/$NAME
PIDFILE=/var/run/$NAME.pid
CONF=/etc/$NAME/httpd.conf
APACHECTL=/usr/sbin/${NAME}ctl
# note: SSD is required only at startup of the daemon.
SSD=`which start-stop-daemon`
ENV="env -i LANG=C PATH=/bin:/usr/bin:/usr/local/bin"

# Check that we're not being started by inetd
if egrep -q -i "^[[:space:]]*ServerType[[:space:]]+inet" $CONF
then
    exit 0
fi

test_config() {
    if [ ! -x $APACHECTL ]; then
	log_begin_msg "$APACHECTL is not executable, exiting..."
	log_end_msg 1
    fi

    # ensure we don't leak environment vars into apachectl
    APACHECTL="$ENV $APACHECTL"

    if ! $APACHECTL configtest 2> /dev/null
    then
        log_begin_msg "Configuration syntax error detected, not starting/reloading..."
        [ "$VERBOSE" != "no" ] && echo "" && $APACHECTL configtest || true
        log_end_msg 1
    fi
}

should_start() {
    if [ ! -x $DAEMON ]; then
	log_begin_msg "$DAEMON is not executable, not starting/reloading..."
	log_end_msg 1
    fi
}

case "$1" in
  start)
    should_start
    test_config
    log_begin_msg "Starting $NAME 1.3 web server..."
    if $ENV $SSD --start --pidfile $PIDFILE --exec $DAEMON --oknodo > /dev/null; then
      log_end_msg 0
    else
      log_end_msg 1
    fi
    ;;

  stop)
    log_begin_msg "Stopping $NAME 1.3 web server..."
    if $ENV $SSD --stop --pidfile $PIDFILE --oknodo; then
      rm -rf /var/lib/apache/mod-bandwidth/link/*
      log_end_msg 0
    else
      rm -rf /var/lib/apache/mod-bandwidth/link/*
      log_end_msg 1
    fi
    ;;

  reload | force-reload)
    test_config
    log_begin_msg "Reloading $NAME 1.3 configuration..."
    if $ENV $SSD --stop --pidfile $PIDFILE --signal USR1 --oknodo > /dev/null; then
      log_end_msg 0
    else
      log_end_msg 1
    fi
    ;;

  reload-modules)
    should_start
    test_config
    log_begin_msg "Reloading $NAME 1.3 modules..."
    if start-stop-daemon --stop --pidfile $PIDFILE --oknodo --retry 30; then
      if $ENV $SSD --start --pidfile $PIDFILE --exec $DAEMON > /dev/null; then
        log_end_msg 0
      else
        log_end_msg 1
      fi
    else
      log_end_msg 1
    fi
    ;;

  restart)
    test_config
    log_begin_msg "Restarting $NAME 1.3 web server..."
    if ! start-stop-daemon -q --stop --pidfile $PIDFILE --signal HUP; then
      if $ENV $SSD --start --pidfile $PIDFILE --exec $DAEMON --oknodo > /dev/null; then
        log_end_msg 0
      else
        log_end_msg 1
      fi
    else
      log_end_msg 0
    fi
    ;;

  *)
    echo "Usage: /etc/init.d/$NAME {start|stop|reload|reload-modules|force-reload|restart}"
    exit 1
    ;;
esac

