#!/bin/bash
#
# Copyright (c) 2020-2023 by the Zeek Project. See LICENSE for details.
#
# Tool to update autogenerated docs that require the Zeek integration. 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") <zeek-source-code> <spicy-tftp-repo>"
    exit 1
fi

zeek=$1
tftp=$2

if [ ! -e "${zeek}"/scripts/spicy/zeek.spicy ]; then
    echo "${zeek} does not seem to point to a (recent) Zeek 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  < "${zeek}/scripts/spicy/zeek.spicy" > "${AUTOGEN_FINAL}/zeek/zeek-functions.spicy" || exit 1

# Copy some static files over.
cp "${zeek}"/scripts/base/frameworks/spicy/init-bare.zeek "${AUTOGEN_FINAL}"/zeek/ || exit 1
cp "${zeek}"/scripts/base/frameworks/spicy/init-framework.zeek "${AUTOGEN_FINAL}"/zeek/ || exit 1
cp "${zeek}"/scripts/policy/frameworks/spicy/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
cat "${tftp}"/analyzer/tftp.spicy | grep -v spicy::accept_input > "${AUTOGEN_FINAL}"/zeek/tftp-no-accept.spicy || exit 1
