#!/bin/bash
#
# Tool to update autogenerated docs that require the Zeek plugin. Because we are no longer
# shipping that with the Spicy distribution, this needs to be called manually.

set -e

if [ $# != 2 ]; then
    echo "usage: $(basename "$0") <spicy-plugin-repository> <spicy-tftp-repo>"
    exit 1
fi

plugin=$1
tftp=$2

if [ ! -e "${plugin}"/spicy/zeek.spicy ]; then
    echo "${plugin} does not seem to point to a spicy-plugin repository."
    exit 1
fi

if [ ! -d "${tftp}"/analyzer ]; then
    echo "${tftp} does not seem to point to a spicy-tftp repository."
    exit 1
fi

set -o errexit
set -o nounset

ROOTDIR="$(cd "$( dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)/../.."
BUILDDIR="${ROOTDIR}/build"
AUTOGEN_FINAL="${ROOTDIR}/doc/autogen"

# Autogen library docs.
if [[ ! -x ${BUILDDIR}/bin/spicy-doc ]]; then
    >&2 echo "Warning: Could not find required executable ${BUILDDIR}/bin/spicy-doc, aborting"
    exit 0
fi

"${ROOTDIR}/doc/scripts/autogen-spicy-lib" functions zeek  < "${plugin}/spicy/zeek.spicy" > "${AUTOGEN_FINAL}/zeek/zeek-functions.spicy" || exit 1

# Copy some static files over.
cp "${plugin}"/scripts/__preload__.zeek "${AUTOGEN_FINAL}"/zeek/ || exit 1
cp "${plugin}"/scripts/Zeek/Spicy/bare.zeek "${AUTOGEN_FINAL}"/zeek/ || exit 1
cp "${plugin}"/scripts/Zeek/Spicy/misc/record-spicy-batch.zeek "${AUTOGEN_FINAL}"/zeek/ || exit 1

cp "${tftp}"/scripts/main.zeek "${AUTOGEN_FINAL}"/zeek/tftp.zeek || exit 1
cp "${tftp}"/analyzer/tftp.spicy "${AUTOGEN_FINAL}"/zeek/tftp.spicy || exit 1
cp "${tftp}"/analyzer/tftp.evt "${AUTOGEN_FINAL}"/zeek/tftp.evt || exit 1
cp "${tftp}"/analyzer/zeek_tftp.spicy "${AUTOGEN_FINAL}"/zeek/zeek_tftp.spicy || exit 1
