#! /bin/bash
### BEGIN INIT INFO
# Provides:          nia 
# Required-Start:    $all 
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Network Injector Appliance 
# Description:       Run NIA 
### END INIT INFO

NAME="Network Injector Appliance"

#  The location of the configuration file for the probe
NIA_CFG_FILE=/opt/td-config/share/rcsredirect.conf

#  The location of the redirector
NIA_RUN=/opt/td-config/bin/RCSRedirect

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

VERBOSE="yes"

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

# Function that starts the daemon/service
do_start()
{
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
	
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting Redirector & Proxy daemon"

	if [ ! -e $NIA_CFG_FILE ] ; then
		[ "$VERBOSE" != no ] && log_daemon_msg "FATAL: Cannot find the configuration file"
		return 2
	fi

	[ "$VERBOSE" != no ] && log_daemon_msg "Starting the Sniffer(s)..."
	sleep 5

	for iface in `grep sniffing_iface $NIA_CFG_FILE | grep -v channel | cut -f 2 -d \"`; do
		[ "$VERBOSE" != no ] && log_daemon_msg "Capturing on $iface..."
		(cd /opt/td-config; $NIA_RUN -w -a $NIA_CFG_FILE)
		sleep 1
		pidof RCSRedirect > /dev/null
	done		

	[ "$VERBOSE" != no ] && log_daemon_msg "Starting capture infections..."
	/opt/td-config/scripts/infect_app.py &

	return 0
}

# Function that stops the daemon/service
do_stop()
{
	# Return
	#   0 if daemon has been stopped
	#   1 if daemon was already stopped
	#   2 if daemon could not be stopped
	#   other if a failure occurred

	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping Redirector & Proxy daemon"

	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping capture infections..."
	pkill -KILL -f infect_app.py 2> /dev/null

	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping the Sniffer(s)..."
	killall -9 RCSRedirect 2> /dev/null
	
	return 0
}

case "$1" in
  start)
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $NAME"
	do_start
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  stop)
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $NAME"
	do_stop
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop}" >&2
	exit 3
	;;
esac

:
