#!/usr/local/bin/bash

# This script is based upon the startup script found in 
# the wonderful snort tutorial written by Keith Tokash.  You 
# can find that at http://www.snort.org/docs/.  The name 
# is "FreeBSD, Mysql, and Snort Tutorial".  Don't forget 
# to check the location of bash on your system or this won't run.

# This script should be placed in the rc.d directory on your OS 
# or whereever startup scripts go normally.

# location of the snort daemon
BASE=/usr/local/bin/snort

# location of the snort conf file
CONF=/usr/local/etc/snort.conf

# the args we use when starting snort
ARGS='-i xl0 -o -u root -g snort -D'

# the pid of the snort daemon.  This requires the pgrep 
# utility which should either come with your OS or be a 
# part of the sysutils ports collection for your OS.
PID=`/usr/local/bin/pgrep snort`

# location of the pid file
PIDFILE=/var/run/snort_xl0.pid

# Check that $BASE exists.
[ -f $BASE ] || exit 0

# make sure the user calling us is root
ID=`id | cut -d'(' -f2 | cut -d')' -f1`
if [ $ID != root ]; then
  echo "You must be root or use sudo (preferably) to run this command."
  exit 0
fi 

# Check for an argument and print a usage statement
case "$1" in
  start)
    if [ -x $BASE ]; then
      # first check to see if snort is already running
      if [ $PID > 0 ]; then
        echo "Snort is already running"
        exit 0
      else
        $BASE -c $CONF $ARGS >/dev/null 2>&1
        echo -n 'Starting snort'
        echo ""
      fi
      sleep 3
      PID=`/usr/local/bin/pgrep snort`
      if [ $PID ]; then
        echo "OK"
        exit 0
      else
        echo "Snort failed to start."
        echo "Check /var/log/messages for errors." # or /var/adm/messages on Solaris
        exit 0
      fi
    fi
  ;;
  stop)
    if [ $PID > 0 ]; then
      /bin/kill $PID >/dev/null 2>&1
      echo 'Stopping snort'
      rm -f $PIDFILE
      sleep 3
      PID=`/usr/local/bin/pgrep snort`
      if [ $PID ]; then
        echo "There was a problem stopping snort." 
        echo "Snort may not have been stopped."
        echo "Check /var/log/messages for errors."
        exit 0
      else
        echo "OK"
        exit 0
      fi
    else
      echo "Snort does not appear to be running."
      exit 0
    fi
  ;;
  restart)
    $0 stop
    $0 start
  ;;
  *)
    echo ""
    echo "Usage: `basename $0` { start|restart|stop }"
    echo ""
    exit 64
    ;;
esac
