#!/bin/bash
set -e
. /usr/share/debconf/confmodule

OK=0
CONFIG=/etc/default/argus-server
PATH=/bin:/sbin:/usr/bin:/usr/sbin
PIDFILE=/var/run/argus.pid
VALIDVALUES="both none dialup boot"

db_get argus/startup || true
DEBSTARTUP=$RET
db_get argus/overwrite_conffile || true
OVERWRITE=$RET
db_stop

if [ ! -f "$CONFIG" -a "$OVERWRITE" = "no" ]; then
    . $CONFIG
fi

for i in $VALIDVALUES; do
    if [ "$i" = "$STARTUP" ]; then
	OK=1
    fi
done

if [ $OK != 1 ]; then
    STARTUP=$DEBSTARTUP
fi

PPP_INTERFACES=`ifconfig -a | awk '{print $1}' | grep ppp || true`

case "$1" in
	install)
	    ;;
	upgrade)
		if [ -f $PIDFILE ] && [ -n `ps ax | grep ^\`cat $PIDFILE\` | grep argus` ]; then
		    invoke-rc.d argus-server stop /dev/null 2>/dev/null  || true
		elif [ "$STARTUP" = "dialup" ] || [ "$STARTUP" = "both" ]; then
		    for i in $PPP_INTERFACES; do
			echo -n "Stopping network auditing daemon on $i: "
			test -f /var/run/argus.${i} && \
			    PPP_IFACE=$i /etc/ppp/ip-down.d/argus-server > /dev/null 2>&1 || true
			    echo "argus."
		    done
		fi
	    ;;
	configure)
		# Remove old /etc/logrotate.d/argus file left after 2.0.6.rc3-2
		if [ -e /etc/logrotate.d/argus ] && [ -e /etc/logrotate.d/argus-server ]; then
			rm -f /etc/logrotate.d/argus
		fi
		update-rc.d argus-server defaults 20 > /dev/null
		if [ "$STARTUP" = "none" ]; then
		    invoke-rc.d argus-server stop /dev/null 2>/dev/null || true
		    for i in $PPP_INTERFACES; do
			echo -n "Stopping network auditing daemon on $i: "
			PPP_IFACE=$i /etc/ppp/ip-down.d/argus-server > /dev/null 2>&1|| true
			echo "argus."
		    done
		    INTERFACE=""
		fi
		if [ "$STARTUP" = "dialup" ]; then
		    invoke-rc.d argus-server stop 2>/dev/null || true
		    INTERFACE="ppp0"
		fi
		if [ "$STARTUP" = "boot" ]; then
		    for i in $PPP_INTERFACES; do
			echo -n "Stopping network auditing daemon on $i: "
			PPP_IFACE=$i /etc/ppp/ip-down.d/argus-server > /dev/null 2>&1 || true
			echo "argus."
		    done
		    INTERFACE="eth0"
		    
		fi
		
		if [ ! -f "$CONFIG" -o "$OVERWRITE" = "true" ]; then
				cat << __EOF__ > $CONFIG
# This file is automatically generated. 
# Use dpkg-reconfigure argus-server to modify the settings
STARTUP=$STARTUP
INSTANCE=0
INTERFACE=$INTERFACE
__EOF__
		fi

 		;;
	*)
		#
		#	Unknown action - do nothing.
		#
		exit 0
		;;
esac

if [ "$STARTUP" = "dialup" ] || [ "$STARTUP" = "both" ]; then
    for i in $PPP_INTERFACES; do
	echo -n "Starting network auditing daemon on $i: "
	PPP_IFACE=$i /etc/ppp/ip-up.d/argus-server > /dev/null 2>&1 || true
	echo "argus."
    done
fi

if [ "$STARTUP" = "boot" ] || [ "$STARTUP" = "both" ]; then
    invoke-rc.d argus-server start 2>/dev/null || true
fi

#DEBHELPER#

exit 0
