#!/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
. 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"
}

. ci/scripts/common/nats_env.sh

FX_ENV_NAME="${FX_ENV:-$(resolve_runtime_env_name)}"
load_runtime_env_bundle "${FX_ENV_NAME}"

FX_MONGO_SECRET_PATH="${FX_MONGO_SECRET_PATH:?missing FX_MONGO_SECRET_PATH}"
FX_DEPLOY_TARGET="${FX_DEPLOY_TARGET:?missing FX_DEPLOY_TARGET}"
FX_NEEDS_NATS="${FX_NEEDS_NATS:-}"

if [ -z "${FX_NEEDS_NATS}" ]; then
  case "${FX_DEPLOY_TARGET}" in
    ingestor|oracle) FX_NEEDS_NATS=true ;;
    *) FX_NEEDS_NATS=false ;;
  esac
fi

export FX_MONGO_USER="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${FX_MONGO_SECRET_PATH}" user)"
export FX_MONGO_PASSWORD="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${FX_MONGO_SECRET_PATH}" password)"

if [ "${FX_NEEDS_NATS}" = "true" ]; then
  NATS_URL_VAR=FX_NATS_URL load_nats_env
fi

bash ci/prod/scripts/bootstrap/network.sh
sh ci/scripts/common/ensure_remote_registry_login.sh
bash ci/prod/scripts/deploy/fx.sh "${FX_DEPLOY_TARGET}"
