#!/bin/sh
set -eu

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

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

. ci/scripts/common/runtime_env.sh

normalize_env_file() {
  file="$1"
  tmp="${file}.tmp.$$"
  tr -d '\r' <"$file" >"$tmp"
  mv "$tmp" "$file"
}

load_env_file() {
  file="$1"
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      ''|\#*) continue ;;
    esac
    key="${line%%=*}"
    value="${line#*=}"
    key="$(printf '%s' "$key" | tr -d '[:space:]')"
    value="${value#"${value%%[![:space:]]*}"}"
    value="${value%"${value##*[![:space:]]}"}"
    export "$key=$value"
  done <"$file"
}

VAULT_ENV_NAME="${VAULT_ENV:-$(resolve_runtime_env_name)}"
load_runtime_env_bundle "${VAULT_ENV_NAME}"

SEED_FILE=".dev-vault-seed.env"

cleanup() {
  rm -f "${SEED_FILE}"
}
trap cleanup EXIT INT TERM

seed_field() {
  var_name="$1"
  secret_path="$2"
  field_name="$3"
  optional="${4:-0}"

  if [ "${optional}" = "1" ]; then
    value="$(CI_VAULT_SOURCE=external ./ci/vlt kv_get kv "${secret_path}" "${field_name}" 2>/dev/null || true)"
  else
    value="$(CI_VAULT_SOURCE=external ./ci/vlt kv_get kv "${secret_path}" "${field_name}")"
  fi

  printf '%s=%s\n' "${var_name}" "$(printf '%s' "${value}" | base64 | tr -d '\n')" >> "${SEED_FILE}"
}

: > "${SEED_FILE}"
chmod 600 "${SEED_FILE}"

seed_field REGISTRY_USER_B64 registry user
seed_field REGISTRY_PASSWORD_B64 registry password
seed_field SENDICO_DB_USER_B64 sendico/db user
seed_field SENDICO_DB_PASSWORD_B64 sendico/db password
seed_field SENDICO_DB_KEY_B64 sendico/db key
seed_field SENDICO_NATS_USER_B64 sendico/nats user
seed_field SENDICO_NATS_PASSWORD_B64 sendico/nats password
seed_field SENDICO_API_ENDPOINT_SECRET_B64 sendico/api/endpoint secret
seed_field NOTIFICATION_MAIL_USER_B64 sendico/notification/mail user
seed_field NOTIFICATION_MAIL_PASSWORD_B64 sendico/notification/mail password
seed_field NOTIFICATION_TELEGRAM_BOT_TOKEN_B64 sendico/notification/telegram bot_token
seed_field NOTIFICATION_TELEGRAM_CHAT_ID_B64 sendico/notification/telegram chat_id
seed_field NOTIFICATION_TELEGRAM_THREAD_ID_B64 sendico/notification/telegram thread_id 1
seed_field CHAIN_GATEWAY_RPC_URL_B64 sendico/gateway/chain arbitrum_rpc_url
seed_field CHAIN_GATEWAY_WALLET_PRIVATE_KEY_B64 sendico/gateway/chain/wallet private_key
seed_field CHAIN_GATEWAY_WALLET_ADDRESS_B64 sendico/gateway/chain/wallet address 1
seed_field TRON_GATEWAY_RPC_URL_B64 sendico/gateway/tron rpc_url
seed_field TRON_GATEWAY_GRPC_URL_B64 sendico/gateway/tron grpc_url 1
seed_field TRON_GATEWAY_GRPC_TOKEN_B64 sendico/gateway/tron grpc_token 1

export DEV_VAULT_SEED_FILE="${SEED_FILE}"

bash ci/prod/scripts/deploy/vault.sh
