#!/bin/sh
# chkconfig: 2345 99 33
# description: SNARE System iNtrusion Analysis and Reporting Environment
# processname: snareapache
# config: /etc/snare/epilog/apache.conf
########################################################################
#
#   (c) 2001-2006 Intersect Alliance Pty Ltd
#
#   This script controls SnareApache for UNIX
#
#   Version 2.0
#
#   Usage: /etc/init.d/snareapached { start | stop | restart } 
#
########################################################################

case "$1" in
'start')
        PID=`cat /var/run/snareapache.pid 2>/dev/null`
        if [ ! -z "$PID" ] ;  then
		echo "SnareApache already running. Please stop SnareApache first."
		exit 1
	fi

	id | grep '^uid=0' > /dev/null
	if [ $? -ne 0 ]; then
		echo "Sorry, you need to be root to start snareapache."
		exit 1
	fi

        if [ -f /usr/bin/snareapache ] ; then
                echo "SnareApache starting."
		/usr/bin/snareapache -c /etc/snare/epilog/apache.conf
        fi
	exit 0
        ;;
'stop')
	id | grep '^uid=0' > /dev/null
	if [ $? -ne 0 ]; then
		echo "Sorry, you need to be root to start snareapache."
		exit 1
	fi

        PID=`cat /var/run/snareapache.pid 2>/dev/null`
       	if [ ! -z "$PID" ] ;  then
		kill -USR1 ${PID}
		sleep 1
		kill ${PID}
	fi
	rm -f /var/run/snareapache.pid 2>/dev/null
	sleep 1

	# Just in case:
	# Kill all snareapache processes, sorted on parent process ID
	# This way snareapache with ppid of 1 gets killed first
        ps -e -u 0 -o "pid,ppid,comm"|grep "snareapache" |grep -v grep|egrep -v snareapache[d_]|sort -n +1|awk '{print $1}' |
		while read pid ppid command; do
			if [ ! -z "$pid" ] ; then
				echo "Cleaning up snareapache process $pid"
				kill ${pid} 1>/dev/null 2>&1
			fi
		done
	exit 0
        ;;
'restart')
        if [ -f /etc/init.d/snareapached ] ; then
		/etc/init.d/snareapached stop
		RC=$?
		if [ $RC -gt 0 ]; then
			exit $RC
		fi
		/etc/init.d/snareapached start
		RC=$?
		if [ $RC -gt 0 ]; then
			exit $RC
		fi
	fi
	;;
	
*)
        echo 'Usage: /etc/init.d/snareapached { start | stop | restart }'
        ;;
esac

exit 0
