#!/bin/bash
# SPDX-FileCopyrightText: 2026 Nils Meyer
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Forced command for barman-wal-restore keys, installed by iackit.main.barman.
# Arguments: the barman servers this key may read WAL of. Anything but a
# get-wal of a WAL or history file of one of them is refused, in particular
# options that make barman write (--output-dir) or read another
# configuration (--config).
set -euo pipefail

deny() {
  logger -t i4t-barman-get-wal -p auth.warning \
    "DENY $*: ${SSH_ORIGINAL_COMMAND:-<none>} (allowed: ${allowed[*]:-none})"
  echo "i4t-barman-get-wal: refused: $*" >&2
  exit 1
}

allowed=("$@")
(( ${#allowed[@]} > 0 )) || deny "no server allowed"

# barman-wal-restore sends: barman get-wal [options] 'server' 'wal'
# read -a splits on whitespace without globbing; the single quotes it puts
# around values are stripped below, and nothing here contains quotes or
# whitespace of its own.
read -r -a argv <<< "${SSH_ORIGINAL_COMMAND:-}"
for i in "${!argv[@]}"; do
  v=${argv[i]}
  if [[ $v == \'*\' ]]; then v=${v:1:${#v}-2}; fi
  argv[i]=$v
done

[[ ${#argv[@]} -ge 4 && ${argv[0]} == barman && ${argv[1]} == get-wal ]] || deny "not get-wal"

opts=()
test_only=0
i=2
while (( i < ${#argv[@]} - 2 )); do
  case "${argv[i]}" in
    -z|--gzip|-j|--bzip2|--keep-compression|-P|--partial) opts+=("${argv[i]}") ;;
    -t|--test) opts+=("${argv[i]}"); test_only=1 ;;
    --peek)
      [[ ${argv[i+1]:-} =~ ^[0-9]{1,3}$ ]] || deny "bad peek"
      opts+=(--peek "${argv[i+1]}"); ((i += 1)) ;;
    *) deny "option ${argv[i]}" ;;
  esac
  ((i += 1))
done

server=${argv[-2]}
wal=${argv[-1]}
ok=0
for s in "${allowed[@]}"; do [[ $server == "$s" ]] && ok=1; done
(( ok )) || deny "server $server"
# barman-wal-restore --test sends a dummy WAL name
if ! (( test_only )) || [[ $wal != dummy_wal_name ]]; then
  [[ $wal =~ ^[0-9A-F]{24}(\.partial)?$ || $wal =~ ^[0-9A-F]{8}\.history$ ]] || deny "walname $wal"
fi

logger -t i4t-barman-get-wal -p auth.info "ALLOW $server $wal ${opts[*]}"
exec /usr/bin/barman get-wal "${opts[@]}" "$server" "$wal"
