#!/bin/sh

#
#  File called every 30min on the half-hour by cron, does the following
#
#   1) Waits for exactly half-hour to start (in case cron started a
#       minute early - I've seen it happen)
#   2) Kills previous instance of ipaudit.  Report programs that were
#       waiting for previous ipaudit to end will now run. 
#   3) Starts new instance of ipaudit
#   4) Zips data files
#   5) Erases raw data files created 14 days ago
#   6) Runs reports which read report output and creates summary
#       graphs for web page
#
#   JR 2000-08-09

#
#  Constants
#

IP_DIR=$HOME
IP_DATA=$IP_DIR/data/30min              # ipaudit summary dir
IP_RAW=$IP_DIR/raw/30min                # ioptional ipaudit packet output dir
IP_REPORT=$IP_DIR/reports/30min/traffic # 30min report directory dir

#  Read constants from ipaudit.cfg (LOCAL_NET, GZIP)
. $IP_DIR/ipaudit.cfg


CURDATE_DEF=`$GNUDATE`
CURDATE=`$GNUDATE "+%Y-%m-%d-%H:%M" -d "$CURDATE_DEF"`

#
#  Make sure we start on the half hour - a kludge
#
minute=`$GNUDATE +%M`
if [ $minute -eq 29  -o  $minute -eq 59 ] 
then
   sleep 31
fi


#
#  Signal previous instance to finish up
#  (won't actually die until work is done)
#
if [ -f $IP_DIR/run/ipaudit.pid ]
then
	oldpid=`cat $IP_DIR/run/ipaudit.pid`
	ps hp $oldpid > /dev/null
	if [ $? -ne 0 ]
	then
	   echo '$IP_DIR/ipaudit died prematurely'
	else
	   kill -2 $oldpid
	fi

fi


#
#  Start new sequence of programs started by ipaudit
#    this instance of ipaudit will be 'kill -2' at the start of next 
#    time period.
#    Upon receiving this signal ipaudit will stop gathering data and 
#    print a summary, and stop execution.  The subequent programs will 
#    then be executed in turn
#     
LARG=
if [ -n "$CONN_LIMIT" ]
then
   LARG=-L$CONN_LIMIT;
fi

PARG=
if [ -n "$PORT_LIST" ]
then
   PARG=-p$PORT_LIST;
fi

NARG=
if [ -n "$LOCAL_NET" ]
then
   NARG=-l$LOCAL_NET
fi

if [ -z "$INTERFACE" ]
then
   INTERFACE=eth1
fi

(

#  Gather IP data and summarize (when kill -2 signal received)
#  (Send startup message from pcap library on standard error to /dev/null)
$IP_DIR/bin/ipaudit  \
   -t \
   -i$IP_DIR/run/ipaudit.pid   \
   -w $IP_RAW/$CURDATE.raw  \
   -o $IP_DATA/$CURDATE.txt  \
   $NARG $PARG $LARG $INTERFACE 2> /dev/null

#  Generate report from summary data
for dir in $IP_DIR/reports/30min/* $IP_DIR/reports/30min/local/*
do
   if [ -d $dir -a -f $dir/runcron ]
   then
      cd $dir
      ./runcron $IP_DIR $CURDATE
   fi
done

#  Zip newly created files
$GZIP $IP_RAW/$CURDATE.raw
$GZIP $IP_DATA/$CURDATE.txt
) &


#
#  Erase old raw files
#
OLDDATE=`$GNUDATE "+%Y-%m-%d" -d "$CURDATE_DEF 14 days ago"`
rm $IP_RAW/$OLDDATE*raw.gz 2> /dev/null
