#!/usr/bin/env bash
# The forced command behind the build server's package-mirror key (round 6,
# session r6-mirrors-bronnen).
#
# 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-mirror-receipt
#   panel package (build-deb.sh)   /usr/lib/corecp-panel/corecp-mirror-receipt
#
#   command="/usr/lib/corecp-panel/corecp-mirror-receipt",restrict ssh-ed25519 AAAA… corecp-mirror-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 record is pushed and not pulled
#
# The selective package mirror runs on the build server, because that is the
# only machine in the deployment allowed to talk to Ubuntu's archive and to the
# four vendors. The panel therefore has to be *told* how fresh that mirror is,
# and it cannot go and look: the panel 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 record travels the same
# direction the audit export and the drill receipt already do — the build
# server reaches in, this panel holds no key back — behind a forced command
# that can do exactly one thing.
#
# A key of its own rather than a second verb on the drill's. The two are
# separate facts pushed by separate units, and one key that can store two
# things is a key whose sentence takes two lines.
#
# `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 runs the mirror, 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 package-mirror record.
# 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:-}" != "mirror" ]; then
  echo "this key may only run: mirror [<hostname>]" >&2
  exit 2
fi

# A hostname and nothing else. Anything with another shape is dropped rather
# than refused: the record 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 mirror --stdin \
  --host "$host" \
  --config /etc/corecp-panel/panel.yaml
