#!/usr/bin/env bash
# The forced command behind the build server's audit-forwarding key (spec §C5).
#
# Installed on panel1 as /usr/local/sbin/corecp-audit-export and named in
# /root/.ssh/authorized_keys:
#
#   command="/usr/local/sbin/corecp-audit-export",restrict ssh-ed25519 AAAA… corecp-audit-pull
#
# `restrict` turns off every forwarding, every tty and the agent; `command=`
# means whatever the client asks for is ignored and this runs instead. So the
# build server's key can read the audit log with two integer arguments and
# cannot do anything else with root on this machine — which is what makes the
# off-box archive worth having: it is written by a host the panel cannot reach,
# with a key that cannot write back.
#
# It is read-only by construction. `corecp-panel audit export` has no flag that
# writes an event; the one thing it does change is the forward cursor, which
# exists so that "the archive is forty minutes behind" has an answer.
set -euo pipefail

read -r verb since limit <<<"${SSH_ORIGINAL_COMMAND:-}"

if [ "${verb:-}" != "export" ]; then
  echo "this key may only run: export <since> <limit>" >&2
  exit 2
fi
case "${since:-}" in ''|*[!0-9]*) since=0 ;; esac
case "${limit:-}" in ''|*[!0-9]*) limit=5000 ;; esac
[ "$limit" -gt 20000 ] && limit=20000

exec /usr/bin/corecp-panel audit export \
  --config /etc/corecp-panel/panel.yaml \
  --since "$since" --limit "$limit" --consumer build
