#!/bin/bash
#
# skeleton	Example initscript
#		This file should be used to construct scripts to be
#		placed in /etc/init.d.
#
# Author:	Miquel van Smoorenburg <miquels@cistron.nl>.
#		Ian Murdock <imurdock@gnu.ai.mit.edu>.
#
#		Please remove the "Author" lines above and replace them
#		with your own name if you copy and modify this script.
#
# Version:	@(#)skeleton  2.85-23  28-Jul-2004  miquels@cistron.nl
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Filtering HTTP Proxy"
NAME=CNv4
DAEMON=/usr/sbin/$NAME
PIDFILE=/var/run/cnv4_proxy.pid
SCRIPTNAME=/etc/init.d/cnv4

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 5

test -d /var/run/cnv4 || mkdir /var/run/cnv4
chmod 777 /var/run/cnv4

# Read config file if it is present.
#if [ -r /etc/default/$NAME ]
#then
#	. /etc/default/$NAME
#fi

#
#	Function that starts the daemon/service.
#
d_start() {
    find /tmp -type f -mtime +30 -exec rm {} \;
    ulimit -c unlimited
    # increase neighbour table sizes
    echo 4096 > /proc/sys/net/ipv4/neigh/default/gc_thresh3
    echo 2048 > /proc/sys/net/ipv4/neigh/default/gc_thresh2
    echo 1024 > /proc/sys/net/ipv4/neigh/default/gc_thresh1
    start-stop-daemon --background --start --quiet --oknodo --exec $DAEMON
}

#
#	Function that stops the daemon/service.
#
d_stop() {
    start-stop-daemon --oknodo --retry -2/1/-2/3/-9 --quiet --stop --pidfile $PIDFILE --name $NAME || true
    if [ -e $PIDFILE ]; then
	rm $PIDFILE
    fi
    echo -n "Proxy shutdown complete." > /var/run/cnv4/proxy_status
}

#
#	Function that sends a SIGHUP to the daemon/service.
#
d_reload() {
	start-stop-daemon --stop --quiet --pidfile $PIDFILE \
		--name $NAME --signal 1
}

case "$1" in
  start)
	echo -n "Starting $DESC: $NAME"
	d_start
	sleep 4
	echo "."
	;;
  stop)
	echo -n "Stopping $DESC: $NAME"
	d_stop
	echo "."
	;;
  status)
	if [ ! -e $PIDFILE ]; then
	  exit 3
        fi
	PROXYPID=`cat $PIDFILE`
	if [ -e /proc/$PROXYPID ]; then 
  	  PSTATUS=`fgrep -c CNv4 /proc/$PROXYPID/status`
        else
          PSTATUS=0
        fi
	if [ "$PSTATUS" -ne "1" ]; then
          exit 3
        fi
	exit 0
	;;
  #reload)
	#
	#	If the daemon can reload its configuration without
	#	restarting (for example, when it is sent a SIGHUP),
	#	then implement that here.
	#
	#	If the daemon responds to changes in its config file
	#	directly anyway, make this an "exit 0".
	#
	# echo -n "Reloading $DESC configuration..."
	# d_reload
	# echo "done."
  #;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	echo -n "Restarting $DESC: $NAME"
	d_stop
	sleep 4
	d_start
        sleep 4
	echo "."
	;;
  *)
	# echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
