#!/bin/bash
#
# Wrapper script around the actual Zeek invocation. 
#
# run-zeek <pin_cpu> <zeek_args>
#
# pin_cpu:  the CPU number to use, or -1 to not use CPU pinning.
# zeek_args:  Zeek cmd-line arguments.

child=""

sig_handler()
{
    if [ -n "$child" ]; then
        kill -15 $child 2>/dev/null
        echo KILLED 1>&2
    fi

    if [ ! -e .pid ]; then
        # Write -1 so that the "start" helper script knows an error occurred.
        echo -1 >.pid
    fi
}

# Make sure that a ".pid" file exists when this script terminates so that
# the "start" helper script doesn't hang.
trap sig_handler 0

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

pin_cpu=$1
shift

export PATH=${bindir}:${scriptsdir}:$PATH

use_installed_policies=1
. "${scriptsdir}"/set-zeek-path
if [ $? -ne 0 ]; then
    exit 1
fi

if [ ! -f "${zeek}" ]; then
    echo "run-zeek: file not found: ${zeek}" >&2
    exit 1
fi

# Note: on FreeBSD and OpenBSD, "ulimit -d unlimited" outputs an error message
# for a non-root user and doesn't increase the limit.  For root user, it just
# raises the limit up to the system maximum (32GB, by default).  Increasing
# that value on FreeBSD requires editing /boot/loader.conf and rebooting.
LIMIT=${memlimit:-1572864}
ulimit -m $LIMIT
ulimit -d $LIMIT

# Don't attempt to adjust virtual memory size on OpenBSD, because it always
# fails.
if [ "${os}" != "OpenBSD" ]; then
    ulimit -v $LIMIT
    ulimit_v="-v"
fi
ulimit -c unlimited

# Show current limits (visible in crash reports and "zeekctl diag")
ulimit -m -d $ulimit_v -c

echo "PATH=${PATH}" >.env_vars
echo "ZEEKPATH=${ZEEKPATH}" >>.env_vars
echo "CLUSTER_NODE=${CLUSTER_NODE}" >>.env_vars

echo $@ >.cmdline

# Note: the post-terminate script reads the .startup file and expects a certain
# format.
date +%s >.startup
date >>.startup
date +%y-%m-%d_%H.%M.%S >>.startup # Zeek default format when rotating files. 

myzeek=${zeek}
if [ "${havenfs}" = "1" ]; then
    if [ ! -d "${tmpexecdir}" ]; then
        echo "run-zeek: directory not found: ${tmpexecdir}" >&2
        exit 1
    fi
    myzeek=${tmpexecdir}/`basename "${zeek}"`
    rm -f "$myzeek"
    cp -p "${zeek}" "$myzeek"
    if [ $? -ne 0 ]; then
        exit 1
    fi
fi

if [ -n "${pin_command}" ] && [ $pin_cpu -ge 0 ]; then
    # Test if the specified pin_command works, and if not, then output a more
    # useful error message (but let the pin_command output its own error
    # message just in case there's some other reason for the failure).
    ${pin_command} $pin_cpu true
    if [ $? -ne 0 ]; then
        echo "run-zeek: possibly invalid CPU number $pin_cpu given for pin_cpus option" >&2
        exit 1
    fi

    nohup ${pin_command} $pin_cpu "$myzeek" "$@" &
else
    nohup "$myzeek" "$@" &
fi

child=$!

echo $child >.pid
wait $child
child=""
