#!/bin/sh
#
# chkconfig: 345 05 99
# description: The Port Scan Attack Detector (psad)
# processname: psad
# config: psad

# Source function library.
. /etc/rc.d/init.d/functions

psadkillproc() {
	# Test syntax.
	if [ $# = 0 ]; then
		echo "Usage: killproc {program} [signal]"
		return 1
	fi

	notset=0
	# check for second arg to be kill level
	if [ "$2" != "" ] ; then
		killlevel=$2
	else
		notset=1
		killlevel="-9"
	fi

        # Save basename.
        base=`basename $1`

        # Find pid.
        pid=`psadpidofproc $base`

        # Kill it.
        if [ "$pid" != "" ] ; then
                [ $BOOTUP = "verbose" ] && echo -n "$base "
		if [ "$notset" = "1" ] ; then
		       if ps h $pid>/dev/null 2>&1; then
			   # TERM first, then KILL if not dead
			   kill -TERM $pid
			   usleep 100000
			   if ps h $pid >/dev/null 2>&1 ; then
				sleep 1
				if ps h $pid >/dev/null 2>&1 ; then
				        sleep 3
					if ps h $pid >/dev/null 2>&1 ; then
					   kill -KILL $pid
					fi
				fi
			   fi
		        fi
			ps h $pid >/dev/null 2>&1 && failure "$base shutdown" || success "$base shutdown"
		# use specified level only
		else
		        if ps h $pid >/dev/null 2>&1; then
	                	kill $killlevel $pid && success "$base $killlevel" || failure "$base $killlevel"
			fi
		fi
	else
	    failure "$base shutdown"
	fi

        # Remove pid file if any.
	if [ "$notset" = "1" ]; then
            rm -f /var/run/$base.pid
	fi
}

# A function to find the pid of a program.
psadpidofproc() {

# psad addition: "pidof -x" to get parent process... this is used by
# the Port Scan Attack Detector.

        # Next try "pidof"
        pid=`pidof -x $1`
        if [ "$pid" != "" ] ; then
                echo $pid
                return 0
        fi
}


if grep -q psadfifo /etc/syslog.conf; then

	# See how we were called.
	case "$1" in
  	start)
		echo -n "Starting the kmsgs daemon: "
		daemon /usr/local/bin/kmsgsd
		echo
		echo -n "Starting the psad daemon: "
		daemon /usr/local/bin/psad -s /etc/psad/psad_signatures
		echo
		echo -n "Starting the disk monitoring daemon: "
		daemon /usr/local/bin/diskmond
		echo
		;;
  	stop)
		echo -n "Shutting down the kmsgs daemon: "
		psadkillproc kmsgsd
		echo 
		echo -n "Shutting down the psad daemon: "
		psadkillproc psad 
		echo
		echo -n "Shutting down the disk monitoring daemon: "
		psadkillproc diskmond
		echo
		;;
  	status)
		status kmsgsd
		status psad 
		status diskmond
		;;
  	restart|reload)
		$0 stop
		$0 start
		;;
	
  	*)
		echo "Usage: psad-init {start|stop|status|restart|reload}"
		exit 1
	esac

else
	echo "Syslog has not been configured to send kern.info messages to"
	echo "/var/log/psadfifo.  Do you need to run the psad installer?"
fi
