#! /usr/bin/env bash 
#
# $Id: post-terminate.in 6813 2009-07-07 18:54:12Z robin $
#
# Cleans-up after termination.
#
# post-terminate <dir> [crash]
#
# If $2 is "crash", then the scripts assumes that Bro crashed and will return
# information about the crash on stdout which is suitable for mailing to the user. 

dir=$1

crash=0
if [ "$2" == "crash" ]; then
   crash=1
fi   

if [ ! -d $dir ]; then
   echo No $dir
   exit
fi

date=`date +%Y-%m-%d-%H-%M-%S`
tmp=/var/spool/bro/tmp/post-terminate-$date-$$

if [ "$crash" = "1" ]; then
   cd $1
   /usr/share/broctl/scripts/crash-diag $dir
   tmp=$tmp-crash
   archive_flags="-c" # Don't delete log files in work dir.
fi    

if [ ! -d /var/spool/bro/tmp ]; then 
   mkdir /var/spool/bro/tmp 
fi

mv $dir $tmp 2>/dev/null

mkdir $dir 2>/dev/null

if [ -d $tmp/.state ]; then
   mv $tmp/.state $dir 2>/dev/null
fi   

cd $tmp

if [ "$crash" = "1" ]; then
   tmpbro=/var/spool/bro/tmp/`basename /usr/bin/bro`
   cp $tmpbro .
fi

# Run post-processors manually. 

if [ ! -f .startup ]; then
   echo No .startup
   exit
fi

end=`date +%y-%m-%d_%H.%M.%S`
start=`cat .startup | tail -1`
if [ "$crash" = "1" -a -e .rotate ]; then
   start=`cat .rotate | tail -1`
fi   

#if [ -e .peer_description ]; then
#   tag=`cat .peer_description | tail -1`
#fi   

( for i in *.log; do
    if [ -s $i ]; then
       /usr/share/broctl/scripts/archive-log $archive_flags $i $i $start $end $tag >/dev/null &
    fi
  done && wait && if [ "$crash" = "0" ]; then rm -rf $tmp; fi ) &



