#! /usr/bin/env bash
#
# Check Bro's configuration for errors.
#
# check-config <use_installed_policies> <print_loaded_scripts> <cwd> <bro_opts>
#
# use_installed_policies:  1 to use local policy files installed by
#                          "broctl install", or 0 to use the original files
# print_loaded_scripts:  1 to output loaded_scripts.log, or 0 to not output
# cwd:  directory name to run Bro from
# bro_opts:  string containing Bro cmd-line options

if [ $# -lt 4 ]; then
    echo "check-config: missing arguments"
    exit 1
fi

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

use_installed_policies=$1
print_loaded_scripts=$2
tmp_node_dir=$3
shift 3

source "${scriptsdir}"/set-bro-path
if [ $? -ne 0 ]; then
    exit 1
fi

if [ ! -f "${bro}" ]; then
    echo "check-config: file not found: ${bro}"
    exit 1
fi

# Tell the BroControl script code that this is only a check.
export BROCTL_CHECK=1

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

cd "$tmp_node_dir"
if [ $? -ne 0 ]; then
    exit 1
fi

echo $@ >.cmdline
touch .checking

"${bro}" "$@"
rc=$?

if [ $rc -eq 0 -a "$print_loaded_scripts" = "1" ]; then
    grep -v '^#' loaded_scripts*
fi

exit $rc
