#! /bin/sh

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

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

NAME=varnishlog
DESC="HTTP accelerator log deamon"
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/$NAME/$NAME.pid
LOGFILE=/var/log/varnish/varnish.log
USER=varnishlog
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 "${VARNISHLOG_ENABLED}" ] || \
   [ "${VARNISHLOG_ENABLED}" = "0" ] || \
   [ "${VARNISHLOG_ENABLED}" = "no" ]; then
  exit 0;
fi

test -x $DAEMON || exit 0

start_varnishlog() {
    output=$(/bin/tempfile -s.varnish)
    log_daemon_msg "Starting $DESC" "$NAME"
    create_pid_directory
    if start-stop-daemon --start --quiet --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
}

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

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

status_varnishlog(){
    status_of_proc -p "${PIDFILE}" "${DAEMON}" "${NAME}"
    exit $?
}

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

case "$1" in
    start)
        start_varnishlog
	;;
    stop)
        stop_varnishlog
        ;;
    reload)
        reload_varnishlog
        ;;
    status)
        status_varnishlog
	;;
    restart|force-reload)
	$0 stop
	$0 start
        ;;
    *)
        log_success_msg "Usage: $0 {start|stop|restart|force-reload|reload}"
        exit 1
        ;;
esac

exit 0
