#!/usr/bin/env bash
# The forced command behind the repository host's key on panel1 (spec §C6).
#
# pgBackRest's repository host connects here and asks to run its own binary in
# remote mode. Without a forced command that key would be a shell on the control
# plane; with one, it is exactly the protocol pgBackRest speaks and nothing else.
#
# The check is deliberately narrow: the command must start with the pgbackrest
# binary and must not contain a shell metacharacter. pgBackRest's remote
# invocation is a fixed shape (`pgbackrest --…=… … remote`), so anything that is
# not that shape is either a version this wrapper has not seen — which fails
# loudly and gets fixed — or somebody trying, which fails and is logged.
set -uo pipefail

CMD=${SSH_ORIGINAL_COMMAND:-}
LOG=/var/log/pgbackrest/remote-refused.log

refuse() {
  printf '%s refused: %s\n' "$(date -u +%FT%TZ)" "$1" >> "$LOG" 2>/dev/null || true
  echo "this key may only run the pgbackrest remote protocol" >&2
  exit 2
}

case "$CMD" in
  "sudo -u postgres pgbackrest "*|"pgbackrest "*|"/usr/bin/pgbackrest "*) ;;
  *) refuse "$CMD" ;;
esac
case "$CMD" in
  *';'*|*'&'*|*'|'*|*'`'*|*'$('*|*'<('*|*$'\n'*) refuse "$CMD" ;;
esac

exec /bin/bash -c "$CMD"
