#! /bin/sh

### BEGIN INIT INFO
# Provides:          vinylncsa
# Required-Start:    $local_fs $remote_fs $network vinyl
# Required-Stop:     $local_fs $remote_fs $network vinyl
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start HTTP accelerator log daemon
# Description:       This script provides logging for vinyl
### END INIT INFO

# Source function library
. /lib/lsb/init-functions

NAME=vinylncsa
DESC="HTTP accelerator log deamon"
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/$NAME
PIDFILE=/run/$NAME/$NAME.pid
LOGFILE=/var/log/vinyl/vinylncsa.log
USER=vinyllog
GROUP=vinyl
DAEMON_OPTS="-a -w ${LOGFILE} -D -P ${PIDFILE}"

# Include defaults if available
if [ -f /etc/default/$NAME ] ; then
        . /etc/default/$NAME
fi

# If unset, or set to "0" or "no", exit
if [ -z "${VINYLNCSA_ENABLED}" ] || \
   [ "${VINYLNCSA_ENABLED}" = "0" ] || \
   [ "${VINYLNCSA_ENABLED}" = "no" ]; then
  exit 0;
fi

test -x $DAEMON || { echo "${DAEMON} has no execute bit"; exit 0; }

start_vinylncsa() {
    output=$(/bin/tempfile -s.vinyl)
    log_daemon_msg "Starting $DESC" "$SERVICE"
    create_pid_directory
    if start-stop-daemon --start --pidfile ${PIDFILE} \
        --chuid $USER --exec ${DAEMON} -- ${DAEMON_OPTS} \
        > ${output} 2>&1; then
	log_end_msg 0
    else
	log_end_msg 1
	cat $output
	exit 1
    fi
    rm $output
}

disabled_vinylncsa() {
    log_daemon_msg "Not starting $DESC" "$SERVICE"
    log_progress_msg "disabled in /etc/default/vinylncsa"
    log_end_msg 0
}

stop_vinylncsa(){
    log_daemon_msg "Stopping $DESC" "$SERVICE"
    if start-stop-daemon --stop --pidfile $PIDFILE \
        --retry 10 --exec $DAEMON; then
	log_end_msg 0
    else
	log_end_msg 1
    fi
}

reload_vinylncsa(){
    log_daemon_msg "Reloading $DESC" "$SERVICE"
    if kill -HUP $(cat $PIDFILE) >/dev/null 2>&1; then
	log_end_msg 0
    else
	log_end_msg 1
	exit 1
    fi
}

status_vinylncsa(){
    status_of_proc -p "${PIDFILE}" "${DAEMON}" "${SERVICE}"
    exit $?
}

create_pid_directory() {
    install -o $USER -g $GROUP -d $(dirname $PIDFILE)
}

case "$1" in
    start)
        case "${VINYLNCSA_ENABLED:-}" in
            [Yy]es|[Yy]|1|[Tt]|[Tt]rue)
                start_vinylncsa
                ;;
            *)
                disabled_vinylncsa
                ;;
        esac
	;;
    stop)
        stop_vinylncsa
        ;;
    reload)
        reload_vinylncsa
        ;;
    status)
        status_vinylncsa
	;;
    restart|force-reload)
	$0 stop
	$0 start
        ;;
    *)
        log_success_msg "Usage: $0 {start|stop|restart|force-reload|reload}"
        exit 1
        ;;
esac
