#! /usr/bin/env bash
#
# 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.

. `dirname $0`/broctl-config.sh

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=${tmpdir}/post-terminate-$date-$$

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

if [ ! -d ${tmpdir} ]; then
   mkdir ${tmpdir}
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
   mybro=${bro}
   if [ "${havenfs}" -ne 0 ]; then
       mybro=${tmpexecdir}/`basename ${bro}`
   fi
   cp $mybro .
fi

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

( for i in *.log; do

    if [ "$crash" = "1" ]; then
        # manually run log postprocessors in event of crash
        basename=`echo $i | sed 's/\.log$//g'`
        strt=`cat .startup | tail -1`
        if [ -e .rotated.$basename ]; then
            strt=`cat .rotated.$basename`
        fi
        end=`date +%y-%m-%d_%H.%M.%S`
        ${scriptsdir}/archive-log $archive_flags "$i" "$basename" "$strt" "$end" 1 ascii >/dev/null &
    fi

    ${scriptsdir}/remove-link-for-log $i

  done && wait && if [ "$crash" = "0" ]; then rm -rf $tmp; fi ) &



