#! /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

( function waitforarchivelog() {
    [ "$crash" = "1" ] && return 0

    # Gather list of all archive-log PID files.
    pidfiles=$(find . -maxdepth 1 -name '.archive-log.*.tmp' -type f -print)

    while [ -n "$pidfiles" ]; do
        for pfile in $pidfiles ; do
            # If PID file is empty, then check it again later.
            if [ -s $pfile ]; then
                # Check if a process with given PID exists
                ps -p $(cat $pfile) > /dev/null 2>&1
                if [ $? -ne 0 ]; then
                    # No such process exists, so remove PID file
                    rm -f $pfile
                fi
            fi
        done

        sleep 1

        pidfiles=$(find . -maxdepth 1 -name '.archive-log.*.tmp' -type f -print)
    done

    # Check if any log files remain (this could happen if the archival
    # failed, or if archive-log terminated before a log was archived).
    if [ -z "$(find . -maxdepth 1 -name '*.*-*.log' -type f -print)" ]; then
        rm -rf $tmp
    fi

  }

  for i in *.log; do

    if [ "$crash" = "1" ]; then
        # In the event of a crash, manually run log postprocessors on all
        # remaining logs (including stderr.log and stdout.log).
        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 && waitforarchivelog ) &



