#!/usr/bin/env bash
set -euo pipefail

if (($# < 1)); then
  printf 'Usage: %s <read-only-wp-command> [arguments]\n' "$0" >&2
  exit 64
fi

command_key="${1}${2:+ $2}"
case "$command_key" in
  "core version"|"core is-installed"|"plugin list"|"theme list"|"option get"|"post list"|"user list"|"site list")
    ;;
  *)
    printf 'Command is not in the read-only allowlist.\n' >&2
    exit 64
    ;;
esac

for argument in "$@"; do
  case "$argument" in
    --exec|--exec=*|--require|--require=*|--ssh|--ssh=*|--http|--http=*|--path|--path=*)
      printf 'WP-CLI global execution options are not allowed.\n' >&2
      exit 64
      ;;
  esac
done

: "${WP_SSH_HOST:?WP_SSH_HOST is required.}"
: "${WP_SSH_PORT:?WP_SSH_PORT is required.}"
: "${WP_SSH_USER:?WP_SSH_USER is required.}"
: "${WP_SSH_KEY_PATH:?WP_SSH_KEY_PATH is required.}"
: "${WP_SSH_KNOWN_HOSTS_PATH:?WP_SSH_KNOWN_HOSTS_PATH is required.}"
: "${WP_REMOTE_PATH:?WP_REMOTE_PATH is required.}"

if [[ ! -r "$WP_SSH_KEY_PATH" ]]; then
  printf 'The SSH key is not readable.\n' >&2
  exit 66
fi
if [[ ! -r "$WP_SSH_KNOWN_HOSTS_PATH" ]]; then
  printf 'The known-hosts file is not readable.\n' >&2
  exit 66
fi

printf -v remote_command '%q ' wp "--path=${WP_REMOTE_PATH}" "$@"
ssh -F none \
  -p "$WP_SSH_PORT" -i "$WP_SSH_KEY_PATH" \
  -o BatchMode=yes \
  -o IdentitiesOnly=yes \
  -o PreferredAuthentications=publickey \
  -o PasswordAuthentication=no \
  -o KbdInteractiveAuthentication=no \
  -o ClearAllForwardings=yes \
  -o ForwardAgent=no \
  -o PermitLocalCommand=no \
  -o StrictHostKeyChecking=yes \
  -o UserKnownHostsFile="$WP_SSH_KNOWN_HOSTS_PATH" \
  "${WP_SSH_USER}@${WP_SSH_HOST}" \
  "$remote_command"
