#!/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

BFF_ENV_NAME="${BFF_ENV:-$(resolve_runtime_env_name)}"
load_runtime_env_bundle "${BFF_ENV_NAME}"

BFF_MONGO_SECRET_PATH="${BFF_MONGO_SECRET_PATH:?missing BFF_MONGO_SECRET_PATH}"
BFF_API_SECRET_PATH="${BFF_API_SECRET_PATH:?missing BFF_API_SECRET_PATH}"
BFF_VAULT_SECRET_PATH="${BFF_VAULT_SECRET_PATH:?missing BFF_VAULT_SECRET_PATH}"

export MONGO_USER="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${BFF_MONGO_SECRET_PATH}" user)"
export MONGO_PASSWORD="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${BFF_MONGO_SECRET_PATH}" password)"

export API_ENDPOINT_SECRET="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${BFF_API_SECRET_PATH}" secret)"
if [ "${CI_RUNTIME_ENV_NAME:-prod}" != "devserver" ]; then
  export BFF_VAULT_ROLE_ID="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${BFF_VAULT_SECRET_PATH}" role_id)"
  export BFF_VAULT_SECRET_ID="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${BFF_VAULT_SECRET_PATH}" secret_id)"
  if [ -z "${BFF_VAULT_ROLE_ID}" ] || [ -z "${BFF_VAULT_SECRET_ID}" ]; then
    echo "[bff-deploy] vault approle creds are empty for path ${BFF_VAULT_SECRET_PATH}" >&2
    exit 1
  fi
fi

load_nats_env

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