#!/bin/bash
#
# portsentry Start the portsentry Port Scan Detector 
#
# Authors: Craig Rowland <crowland@psionic.com> and Tim Powers <timp@redhat.com>
#
# chkconfig: 345 98 05
# description: PortSentry Port Scan Detector is part of the Abacus Project \
#              suite of tools. The Abacus Project is an initiative to release \
#              low-maintenance, generic, and reliable host based intrusion \
#              detection software to the Internet community.
# processname: portsentry
# configfile: /etc/portsentry/portsentry.conf
# pidfile: /var/run/portsentry.pid

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

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

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

RETVAL=$?

start (){
  #set up the ignore file
  SENTRYDIR=/etc/portsentry
  FINALIGNORE=$SENTRYDIR/portsentry.ignore
  TMPFILE=/var/portsentry/portsentry.ignore.tmp
  # testline is used to see if the initscript has already been run
	if [ -f $FINALIGNORE ] ; then
    cp -f $FINALIGNORE $TMPFILE
    testline=`grep -n "Do NOT edit below this" $TMPFILE | cut --delimiter=":" -f1`
  	if [ -z "$testline" ] ; then
      echo > /dev/null #do nothing
    else
      let headline=$testline-2
		  head -$headline $FINALIGNORE > $TMPFILE
    fi
  fi
  echo '#########################################' >> $TMPFILE
  echo '# Do NOT edit below this line, if you   #' >> $TMPFILE
  echo '# do, your changes will be lost when    #' >> $TMPFILE
  echo '# portsentry is restarted via the       #' >> $TMPFILE
  echo '# initscript. Make all changes above    #' >> $TMPFILE
  echo '# this box.                             #' >> $TMPFILE
  echo '#########################################' >> $TMPFILE

	for i in `/sbin/ifconfig -a | grep inet | awk '{print $2}' | sed 's/addr://'` ; do
    echo $i >> $TMPFILE
  done
  echo '0.0.0.0' >> $TMPFILE

  cp -f $TMPFILE  $SENTRYDIR/portsentry.ignore
  rm -f $TMPFILE
  
  #check for modes defined in the config file
  if [ -s $SENTRYDIR/portsentry.modes ] ; then
    modes=`cut -d "#" -f 1 $SENTRYDIR/portsentry.modes`
  else
    modes="tcp udp"
  fi
  for i in $modes ; do
    action "Starting portsentry -$i: " /usr/sbin/portsentry -$i
    RETVAL=$?
  done
  [ $RETVAL -eq 0 ] && touch /var/lock/subsys/portsentry
  echo
  return $RETVAL
}

stop() {
  #stop daemon
  echo -n "Stopping portsentry: "
  killproc portsentry
  RETVAL=$?
  [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/portsentry
  echo
  return $RETVAL
}

restart() {
  stop
  start
}

case $1 in 
  start)
    start
  ;;
	
  stop)
    stop
  ;;
	
  restart|reload)
    stop
    start
  ;;
	
  condrestart)
    [ -f /var/lock/subsys/portsentry ] && restart || :
  ;;

  status)
    status portsentry
  ;;
  *)
    echo "Usage: portsentry {start|stop|restart|reload|condrestart|status}"
    exit 1
esac
