#!/bin/sh
#
# Startup script to for Snort Network Intrusion Detection
#
# chkconfig: 2345 99 01
# description: Snort Network Intrusion Detection System

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

# Source networking configuration.
. /etc/sysconfig/network

# Pull in /etc/firewall settings
[ -e /etc/firewall ] && source /etc/firewall

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

RETVAL=0
prog="snort"

sng_ifaces_snort()
{
    filter_list()
    {
        retr=""
        loop=1

        while [ $loop -eq 1 ]; do
            IFS="" read -d' ' ifname || loop=0

            [ -z "$ifname" ] && break

            case "$ifname" in
                sngdsp*) continue ;;
                *)
                    if [ -z "$retr" ]; then
                        retr="$ifname"
                    else
                        retr="$retr,$ifname"
                    fi
                ;;
            esac
        done

        echo "$retr"
    }

    echo "$1" | filter_list
}

start() {
	echo -n $"Starting $prog: "
	# Creates a dummy file for /etc/logrotate.d/snort script
	if [ -d /var/log/snort ]; then
		echo "Used for logrotate... do not delete" > /var/log/snort/logrotate
	fi

	if [ -n "$EXTIF" ]; then
		extlist=$(sng_ifaces_snort "$EXTIF")
		daemon /usr/local/nsc/bin/snort-watchdog --start --interfaces "$extlist" -- -c /etc/snort.conf
	else
		daemon /usr/local/nsc/bin/snort-watchdog --start -- -c /etc/snort.conf
	fi

	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/snort
}

stop() {
	echo -n $"Stopping $prog: "
	/usr/local/nsc/bin/snort-watchdog --stop
	RETVAL=$?
	[ $RETVAL -eq 0 ] && success || failure
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/snort
}

check_status() {
	num=1

	status -p $pidfile snort-watchdog
	ret=$?

	while true; do
		if [ $ret -eq 0 ]; then
			ret=1
			for file in `find /var/run/ -name 'snort_*.pid'`; do
				status -p $file $(basename $file .pid | tr '_' '@')
				ret=$?
			done
			if [ $ret -eq 3 ]; then
				echo "snort is not running"
			fi
		fi

		if [ $ret -eq 1 -a $num -le 4 ]; then
			echo "no snort instances running, waiting..."

			tmload=`stat -c '%Z' $pidfile 2>/dev/null`
			tmcurr=`date +'%s' 2>/dev/null`

			[ -z "$tmload" -o -z "$tmcurr" ] && break

			tmdiff=$((tmcurr - tmload))

			if [ $tmdiff -lt 2 ]; then
				sleep 0.5

				ret=0
				num=$((num+1))
				continue
			fi
		fi

		break
	done

	RETVAL=$ret

}

pidfile="/var/run/snort-watchdog.pid"

# See how we were called.
case "$1" in
  start)
	if ! status -p $pidfile snort-watchdog > /dev/null; then
		start
	fi
	;;
  stop)
	if status -p $pidfile snort-watchdog > /dev/null; then
		stop
	fi
	;;
  status)
	check_status
	;;
  condrestart)
	if test -f $pidfile; then
		$0 stop
		$0 start
		RETVAL=$?
	fi
	;;
  restart|reload)
	$0 stop
	$0 start
	RETVAL=$?
	;;
  *)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|reload}"
	exit 1
esac

exit $RETVAL
