#!/usr/bin/env bash
set -euo pipefail
[[ "${DEBUG_DEPLOY:-0}" = "1" ]] && set -x
trap 'echo "[mntx-gateway-deploy] error at line $LINENO" >&2' ERR

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

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
    if printf '%s' "$line" | grep -Eq '^[[:alpha:]_][[:alnum:]_]*='; then
      key="${line%%=*}"
      value="${line#*=}"
      key="$(printf '%s' "$key" | tr -d '[:space:]')"
      value="${value#"${value%%[![:space:]]*}"}"
      value="${value%"${value##*[![:space:]]}"}"
      export "$key=$value"
    fi
  done <"$file"
}

. ci/scripts/common/nats_env.sh

MNTX_GATEWAY_ENV_NAME="${MNTX_GATEWAY_ENV:-$(resolve_runtime_env_name)}"
load_runtime_env_bundle "${MNTX_GATEWAY_ENV_NAME}"

if [ ! -f ./.env.version ]; then
  echo "[mntx-gateway-deploy] .env.version is missing; run version step first" >&2
  exit 1
fi

MNTX_GATEWAY_MONGO_SECRET_PATH="${MNTX_GATEWAY_MONGO_SECRET_PATH:?missing MNTX_GATEWAY_MONGO_SECRET_PATH}"
MNTX_GATEWAY_MONETIX_SECRET_PATH="${MNTX_GATEWAY_MONETIX_SECRET_PATH:-sendico/gateway/monetix}"
MNTX_GATEWAY_NATS_SECRET_PATH="${MNTX_GATEWAY_NATS_SECRET_PATH:-sendico/nats}"


export MNTX_GATEWAY_MONGO_USER="$(./ci/vlt kv_get kv "${MNTX_GATEWAY_MONGO_SECRET_PATH}" user)"
export MNTX_GATEWAY_MONGO_PASSWORD="$(./ci/vlt kv_get kv "${MNTX_GATEWAY_MONGO_SECRET_PATH}" password)"

export MONETIX_PROJECT_ID="$(./ci/vlt kv_get kv "${MNTX_GATEWAY_MONETIX_SECRET_PATH}" project_id)"
export MONETIX_SECRET_KEY="$(./ci/vlt kv_get kv "${MNTX_GATEWAY_MONETIX_SECRET_PATH}" secret_key)"

NATS_SECRET_PATH="${MNTX_GATEWAY_NATS_SECRET_PATH}" load_nats_env

bash ci/prod/scripts/bootstrap/network.sh
sh ci/scripts/common/ensure_remote_registry_login.sh
bash ci/prod/scripts/deploy/mntx_gateway.sh
