#!/bin/sh
set -eu

if ! set -o pipefail 2>/dev/null; then
  :
fi

REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
cd "${REPO_ROOT}"

usage() {
  echo "usage: runtime_kv_get.sh kv_get <mount> <path> <field>" >&2
  exit 64
}

[ "${1:-}" = "kv_get" ] || usage
[ $# -eq 4 ] || usage

MOUNT="$2"
SECRET_PATH="$3"
FIELD="$4"

. ci/scripts/common/runtime_env.sh

runtime_env_name="${CI_TARGET_ENV:-${CI_RUNTIME_ENV_NAME:-$(resolve_runtime_env_name)}}"
vault_source="${CI_VAULT_SOURCE:-runtime}"

if [ "${vault_source}" = "external" ] || [ "${runtime_env_name}" != "devserver" ]; then
  exec ./ci/vlt kv_get "${MOUNT}" "${SECRET_PATH}" "${FIELD}"
fi

runtime_file="$(resolve_runtime_env_file "${runtime_env_name}")"
cleanup_runtime_file=0
case "${runtime_file}" in
  ./.runtime.*.merged.*)
    cleanup_runtime_file=1
    ;;
esac

cleanup() {
  if [ "${cleanup_runtime_file}" -eq 1 ]; then
    rm -f "${runtime_file}"
  fi
}
trap cleanup EXIT INT TERM

normalize_env_file "${runtime_file}"
load_env_file "${runtime_file}"

: "${SSH_USER:?missing SSH_USER}"
: "${SSH_HOST:?missing SSH_HOST}"
: "${REMOTE_BASE:?missing REMOTE_BASE}"
: "${VAULT_DIR:?missing VAULT_DIR}"

SSH_KEY_FILE="${SSH_KEY_FILE:-}"
if [ -z "${SSH_KEY_FILE}" ] || [ ! -f "${SSH_KEY_FILE}" ]; then
  for candidate in /root/.ssh/id_rsa secrets/SSH_KEY; do
    if [ -f "${candidate}" ]; then
      SSH_KEY_FILE="${candidate}"
      break
    fi
  done
fi

if [ -z "${SSH_KEY_FILE}" ] || [ ! -f "${SSH_KEY_FILE}" ]; then
  echo "[runtime-kv-get] ssh key not found; expected /root/.ssh/id_rsa or secrets/SSH_KEY" >&2
  exit 65
fi

b64enc() {
  printf '%s' "$1" | base64 | tr -d '\n'
}

MOUNT_B64="$(b64enc "${MOUNT}")"
SECRET_PATH_B64="$(b64enc "${SECRET_PATH}")"
FIELD_B64="$(b64enc "${FIELD}")"
REMOTE_TARGET="${SSH_USER}@${SSH_HOST}"

SSH_OPTS="
  -i ${SSH_KEY_FILE}
  -o StrictHostKeyChecking=no
  -o UserKnownHostsFile=/dev/null
  -o LogLevel=ERROR
  -o BatchMode=yes
  -o PreferredAuthentications=publickey
  -o ConnectTimeout=10
"

ssh ${SSH_OPTS} "${REMOTE_TARGET}" \
  REMOTE_BASE="${REMOTE_BASE}" \
  VAULT_DIR="${VAULT_DIR}" \
  MOUNT_B64="${MOUNT_B64}" \
  SECRET_PATH_B64="${SECRET_PATH_B64}" \
  FIELD_B64="${FIELD_B64}" \
  sh -s <<'EOSSH'
set -eu

if printf 'AA==' | base64 -d >/dev/null 2>&1; then
  BASE64_DECODE_FLAG='-d'
else
  BASE64_DECODE_FLAG='--decode'
fi

decode_b64() {
  printf '%s' "$1" | base64 "${BASE64_DECODE_FLAG}"
}

MOUNT="$(decode_b64 "${MOUNT_B64}")"
SECRET_PATH="$(decode_b64 "${SECRET_PATH_B64}")"
FIELD="$(decode_b64 "${FIELD_B64}")"
INIT_FILE="${REMOTE_BASE%/}/${VAULT_DIR}/env/vault-init.json"

if [ ! -s "${INIT_FILE}" ]; then
  echo "[runtime-kv-get] dev vault init file not found: ${INIT_FILE}" >&2
  exit 66
fi

INIT_JSON_COMPACT="$(tr -d '\r\n\t ' <"${INIT_FILE}")"
ROOT_TOKEN="$(printf '%s' "${INIT_JSON_COMPACT}" | sed -n 's/.*"root_token":"\([^"]*\)".*/\1/p')"

if [ -z "${ROOT_TOKEN}" ]; then
  echo "[runtime-kv-get] failed to extract dev vault root token from ${INIT_FILE}" >&2
  exit 67
fi

docker exec \
  -e VAULT_ADDR=http://127.0.0.1:8200 \
  -e VAULT_TOKEN="${ROOT_TOKEN}" \
  dev-vault \
  vault kv get -mount="${MOUNT}" -field="${FIELD}" "${SECRET_PATH}"
EOSSH
