#!/bin/sh
set -eu

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

DEST_FILE="${1:-secrets/SSH_KEY}"
DEST_DIR="$(dirname "${DEST_FILE}")"
ENCODED_FILE="${DEST_FILE}.b64"

. ci/scripts/common/runtime_env.sh

env_name="${CI_TARGET_ENV:-$(resolve_runtime_env_name)}"
runtime_file="$(resolve_runtime_env_file "${env_name}")"
cleanup_runtime_file=0
case "${runtime_file}" in
  ./.runtime.*.merged.*)
    cleanup_runtime_file=1
    ;;
esac

cleanup() {
  rm -f "${ENCODED_FILE}"
  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}"

DEPLOY_SSH_KEY_PATH="${DEPLOY_SSH_KEY_PATH:-ops/deploy/ssh_key}"

mkdir -p "${DEST_DIR}"
./ci/vlt kv_to_file kv "${DEPLOY_SSH_KEY_PATH}" private_b64 "${ENCODED_FILE}" 600
base64 -d "${ENCODED_FILE}" > "${DEST_FILE}"
chmod 600 "${DEST_FILE}"
ssh-keygen -y -f "${DEST_FILE}" >/dev/null

printf '[fetch-deploy-ssh-key] env=%s path=%s\n' "${env_name}" "${DEPLOY_SSH_KEY_PATH}" >&2
