#! /bin/sh

### BEGIN INIT INFO
# Provides:          eZ Publish asynchronous publishing daemon
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts instance of eZ Publish asynchronous publishing daemon
# Description:       starts instance of eZ Publish asynchronous publishing daemon using start-stop-daemon
### END INIT INFO

### Configuration
# Do not edit this file to configure the script. Use /etc/ezasynchronouspublisher.conf or bin/sheel/daemon-settings.sh
### End configuration

STARTUP_SCRIPT=$(readlink -f $0)
NAME=`basename $0`

# TODO: Handle this
SITEACCESS=""

# Read configuration files
DEFAULT_CONF="${STARTUP_SCRIPT}.defaults"
GLOBAL_CONF="/etc/default/ezasynchronouspublisher.conf"
LOCAL_CONF="/etc/default/ezasynchronouspublisher/${NAME}.conf"

# Default configuration
if [ -e "${DEFAULT_CONF}" ]; then
    . "${DEFAULT_CONF}"
fi

# Global configuration
if [ -e "${GLOBAL_CONF}" ]; then
    . "${GLOBAL_CONF}"
fi

# Local configuration
if [ -e "${LOCAL_CONF}" ]; then
    . "${LOCAL_CONF}"
fi

DAEMON_OPTS=" -n"
STARTUP_SCRIPT_PATH=`dirname "${STARTUP_SCRIPT}"`
APP_PATH=${STARTUP_SCRIPT_PATH%/bin/startup/*}
DAEMON="${APP_PATH}/bin/php/ezasynchronouspublisher.php"
DESC="eZ Publish asynchronous publishing daemon"
PID_FOLDER="/var/run/ezpublish"
PID_FILE="$PID_FOLDER/${NAME}.pid"
DAEMON_OPTS="${DAEMON_OPTS} --pid-file=${PID_FILE}"

if [ ${SITEACCESS} ]; then
    DAEMON_OPTS="${DAEMON_OPTS} -s ${SITEACCESS}"
fi

# prepend PHP's path if customized
if [ ${PHP_EXECUTABLE}  ]; then
    DAEMON_EXEC="${PHP_EXECUTABLE} ${DAEMON}"
else
    DAEMON_EXEC=${DAEMON}
fi

. /lib/lsb/init-functions

UGID=$(getent passwd $RUN_AS_USER | cut -f 3,4 -d:) || true

# Test existence and executable status of executable
test -x $DAEMON || exit 0

if [ ! -d "${PID_FOLDER}" ]; then
    mkdir "${PID_FOLDER}"
    chown ${RUN_AS_USER} "${PID_FOLDER}"
fi

set -e

d_start() {
        if [ -z "$UGID" ]; then
                log_failure_msg "user \"${RUN_AS_USER}\" does not exist" "$NAME"
                return 1
        fi
        start-stop-daemon -d ${APP_PATH} \
            --chuid ${RUN_AS_USER} \
            --start \
            --pidfile ${PID_FILE} \
            --exec ${DAEMON_EXEC} -- $DAEMON_OPTS
        return $?
}

d_stop() {
        start-stop-daemon --stop --pidfile $PID_FILE

        if [ -f $PID_FILE ]; then rm -f $PID_FILE; fi
        return $?
}

case "$1" in
  start)
        log_daemon_msg "Starting $DESC" "$NAME"
        d_start
        log_end_msg $?
        ;;
  stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        d_stop
        log_end_msg $?
        ;;

  restart|force-reload)
        log_daemon_msg "Restarting $DESC" "$NAME"
        d_stop
        sleep 1
        d_start
        log_end_msg $?
        ;;
  *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0
