#!/usr/bin/env bash
# The forced command behind the drill machine's receipt key (session
# r5-zelfbewaking, requirement R51).
#
# Installed in one of two places, and named in /root/.ssh/authorized_keys
# by the path it has there:
#
#   source deploy (provision.sh)   /usr/local/sbin/corecp-drill-receipt
#   panel package (build-deb.sh)   /usr/lib/corecp-panel/corecp-drill-receipt
#
#   command="/usr/lib/corecp-panel/corecp-drill-receipt",restrict ssh-ed25519 AAAA… corecp-drill-receipt
#
# The package rewrites the binary path on the exec line below to the one it
# installs, /usr/bin/corecp-panel (build-deb.sh, relocate; item 0045).
#
# # Why the receipt is pushed and not pulled
#
# The restore drill runs on the build server, because a control a platform runs
# on itself proves nothing about that platform being gone. The panel therefore
# has to be *told*, and it cannot go and look: panel1 holds no key into the
# build plane and that is the boundary the off-box audit archive is worth
# anything for (spec §D3, infra/build-server/corecp-audit-pull). So the receipt
# travels the same direction the audit export already does — the build server
# reaches in, this panel holds no key back — behind a forced command that can
# do exactly one thing.
#
# `restrict` turns off every forwarding, every tty and the agent; `command=`
# means whatever the client asks for is ignored and this runs instead. The
# client's own command line is read for one optional word, the name of the
# machine that ran the drill, and that word is filtered here rather than
# trusted: it ends up in a stored record and on a screen.
#
# What this key can do with root on the panel: store one restore-drill receipt.
# It cannot read one back, cannot read anything else, and the CLI behind it has
# no flag that names a file.
set -euo pipefail

read -r verb host <<<"${SSH_ORIGINAL_COMMAND:-}"

if [ "${verb:-}" != "drill" ]; then
  echo "this key may only run: drill [<hostname>]" >&2
  exit 2
fi

# A hostname and nothing else. Anything with another shape is dropped rather
# than refused: the receipt is worth storing even from a machine that named
# itself oddly, and the row then says the host is unknown.
case "${host:-}" in
  '' ) host='' ;;
  *[!a-zA-Z0-9.-]* ) host='' ;;
  *) : ;;
esac
[ "${#host}" -gt 253 ] && host=''

exec /usr/bin/corecp-panel selfwatch drill --stdin \
  --host "$host" \
  --config /etc/corecp-panel/panel.yaml
