#!/bin/sh
set -eu

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

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

sh ci/scripts/common/ensure_env_version.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"
}

. ci/scripts/common/nats_env.sh

TRON_GATEWAY_ENV_NAME="${TRON_GATEWAY_ENV:-prod}"
RUNTIME_ENV_FILE="./ci/${TRON_GATEWAY_ENV_NAME}/.env.runtime"

if [ ! -f "${RUNTIME_ENV_FILE}" ]; then
  echo "[tron-gateway-deploy] runtime env file not found: ${RUNTIME_ENV_FILE}" >&2
  exit 1
fi

normalize_env_file "${RUNTIME_ENV_FILE}"
normalize_env_file ./.env.version

load_env_file "${RUNTIME_ENV_FILE}"
load_env_file ./.env.version

TRON_GATEWAY_MONGO_SECRET_PATH="${TRON_GATEWAY_MONGO_SECRET_PATH:?missing TRON_GATEWAY_MONGO_SECRET_PATH}"
TRON_GATEWAY_RPC_SECRET_PATH="${TRON_GATEWAY_RPC_SECRET_PATH:?missing TRON_GATEWAY_RPC_SECRET_PATH}"
TRON_GATEWAY_WALLET_SECRET_PATH="${TRON_GATEWAY_WALLET_SECRET_PATH:?missing TRON_GATEWAY_WALLET_SECRET_PATH}"
TRON_GATEWAY_VAULT_SECRET_PATH="${TRON_GATEWAY_VAULT_SECRET_PATH:?missing TRON_GATEWAY_VAULT_SECRET_PATH}"

export TRON_GATEWAY_MONGO_USER="$(./ci/vlt kv_get kv "${TRON_GATEWAY_MONGO_SECRET_PATH}" user)"
export TRON_GATEWAY_MONGO_PASSWORD="$(./ci/vlt kv_get kv "${TRON_GATEWAY_MONGO_SECRET_PATH}" password)"

export TRON_GATEWAY_RPC_URL="$(./ci/vlt kv_get kv "${TRON_GATEWAY_RPC_SECRET_PATH}" rpc_url)"
export TRON_GATEWAY_GRPC_URL="$(./ci/vlt kv_get kv "${TRON_GATEWAY_RPC_SECRET_PATH}" grpc_url || true)"
export TRON_GATEWAY_GRPC_TOKEN="$(./ci/vlt kv_get kv "${TRON_GATEWAY_RPC_SECRET_PATH}" grpc_token || true)" 

export TRON_GATEWAY_SERVICE_WALLET_KEY="$(./ci/vlt kv_get kv "${TRON_GATEWAY_WALLET_SECRET_PATH}" private_key)"
export TRON_GATEWAY_SERVICE_WALLET_ADDRESS="$(./ci/vlt kv_get kv "${TRON_GATEWAY_WALLET_SECRET_PATH}" address || true)"

export TRON_GATEWAY_VAULT_ROLE_ID="$(./ci/vlt kv_get kv "${TRON_GATEWAY_VAULT_SECRET_PATH}" role_id)"
export TRON_GATEWAY_VAULT_SECRET_ID="$(./ci/vlt kv_get kv "${TRON_GATEWAY_VAULT_SECRET_PATH}" secret_id)"
if [ -z "${TRON_GATEWAY_VAULT_ROLE_ID}" ] || [ -z "${TRON_GATEWAY_VAULT_SECRET_ID}" ]; then
  echo "[tron-gateway-deploy] vault approle creds are empty for path ${TRON_GATEWAY_VAULT_SECRET_PATH}" >&2
  exit 1
fi

load_nats_env

bash ci/prod/scripts/bootstrap/network.sh
bash ci/prod/scripts/deploy/tron_gateway.sh
