#!/bin/sh
#
# RunCache	Run squid, restart it if it died.
#		This is overly cautious - with new versions of
#		squid, it just doesn't die. Oh well.
#
# Version:	@(#)RunCache  2.00  17-Dec-1998  miquels@cistron.nl
#

#
#	Squid gets run with the arguments passed to "RunCache".
#	Set some defaults args if none were passed. If a filename
#	was passed, treat it as configfile location (backwards compat).
#
case "$1" in
	"")
		set -- -D -sNY
		;;
	/*)
		set -- -D -sNY -f "$1"
		;;
esac

PIDFILE=/var/run/runcache.pid
PATH=/usr/lib/squid:/bin:/sbin:/usr/sbin:/usr/bin
L=/var/log/squid/squid.out
export PATH
umask 022

#
#	Just to be sure, check if squid is not already running.
#
if [ -f /var/run/squid.pid ]
then
	spid=`cat /var/run/squid.pid`
	kill -CONT $spid 2>/dev/null
	if [ $? = 0 ]
	then
		#echo "RunCache: squid is already running." >&2
		exit 0
	fi
fi

rm -f $PIDFILE
echo $$ > $PIDFILE

failcount=0
while : ; do
	exec >>$L 2>&1 0</dev/null # (Re) open logfile
	echo "`date`: Running: squid -D -s $conf"
	start=`date '+%d%H%M%S'`
	squid "$@"
	exec >>$L 2>&1 0</dev/null # Re-open logfile
	stop=`date '+%d%H%M%S'`
	t=`expr $stop - $start`
	if test 0 -le $t -a $t -lt 5 ; then
		failcount=`expr $failcount + 1`
	else
		failcount=0
	fi
	if test $failcount -gt 5 ; then
          echo "`date`: RunCache: EXITING DUE TO REPEATED FREQUENT FAILURES"
	  exit 1
	fi
	sleep 10
done

