#!/bin/sh
#
# Varnish cache for the EDRN Public Portal
#
# chkconfig: 345 71 31
# description: Varnish cache

. /etc/rc.d/init.d/functions

# Size is in megabytes
CACHE_SIZE=α
CACHE=β/logs/varnish.cache
LISTEN=80
MGMT=ζ
CONFIG=γ
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=δ
NAME=varnishd
DESC=varnish
TMP=ε

test -x $DAEMON || exit 0

# Check for configuration
if [ ! -f "$CONFIG" ]; then
	echo "varnish config file $CONFIG missing" !>&2
	exit 1
fi

start() {
	if [ -f /var/lock/subsys/$NAME ]; then
		pids=`pidofproc $NAME`
		if checkpid $pids; then
			echo "$DESC already running: $pids" 1>&2
			return 1
		fi
		rm /var/lock/subsys/$NAME
	fi
	if [ ! -f $CACHE ]; then
		/bin/dd if=/dev/zero of=$CACHE bs=1M count=$CACHE_SIZE
	fi
	if action "Starting $DESC" /usr/local/sbin/varnishd -h classic -s file,$CACHE -a 0.0.0.0:$LISTEN -T localhost:$MGMT -p backend_http11=on -p client_http11=on -f $CONFIG; then
		touch /var/lock/subsys/$NAME
		return 0
	fi
	return 1
}

stop() {
	if [ -f /var/lock/subsys/$NAME ]; then
		rc=0
		if [ -x /usr/local/sbin/stop-varnish ]; then
			/usr/local/sbin/stop-varnish $MGMT
		fi
		sleep 1
		if killproc $NAME; then
			rm -f /var/lock/subsys/$NAME
			action "Stopping $DESC" /bin/true
		else
			action "Stopping $DESC" /bin/false
			rc=1
		fi
		return $rc
	else
		echo "$DESC not running" 1>&2
		return 1
	fi
	return 1
}

case "$1" in 
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		if [ -f /var/run/$NAME.pid ]; then
			pid=`cat /var/run/$NAME.pid`
			echo "$DESC running on pid $pid"
			exit 0
		else
			echo "$DESC not running"
		fi
		;;
	restart)
		stop
		start
		;;
	*)
		echo "Usage: $0 {start|stop|status|restart}" 1>&2
		exit 1
		;;
esac
