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

NOTIFICATION_ENV_NAME="${NOTIFICATION_ENV:-$(resolve_runtime_env_name)}"
load_runtime_env_bundle "${NOTIFICATION_ENV_NAME}"

NOTIFICATION_MONGO_SECRET_PATH="${NOTIFICATION_MONGO_SECRET_PATH:?missing NOTIFICATION_MONGO_SECRET_PATH}"
NOTIFICATION_MAIL_SECRET_PATH="${NOTIFICATION_MAIL_SECRET_PATH:?missing NOTIFICATION_MAIL_SECRET_PATH}"
NOTIFICATION_API_SECRET_PATH="${NOTIFICATION_API_SECRET_PATH:?missing NOTIFICATION_API_SECRET_PATH}"
NOTIFICATION_TELEGRAM_SECRET_PATH="${NOTIFICATION_TELEGRAM_SECRET_PATH:?missing NOTIFICATION_TELEGRAM_SECRET_PATH}"

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

export MAIL_USER="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${NOTIFICATION_MAIL_SECRET_PATH}" user)"
export MAIL_SECRET="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${NOTIFICATION_MAIL_SECRET_PATH}" password)"

export API_ENDPOINT_SECRET="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${NOTIFICATION_API_SECRET_PATH}" secret)"

export TELEGRAM_BOT_TOKEN="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${NOTIFICATION_TELEGRAM_SECRET_PATH}" bot_token)"
export TELEGRAM_CHAT_ID="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${NOTIFICATION_TELEGRAM_SECRET_PATH}" chat_id)"
TELEGRAM_THREAD_ID=""
if TELEGRAM_THREAD_ID_VALUE="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${NOTIFICATION_TELEGRAM_SECRET_PATH}" thread_id 2>/dev/null)"; then
  TELEGRAM_THREAD_ID="$TELEGRAM_THREAD_ID_VALUE"
fi
export TELEGRAM_THREAD_ID

load_nats_env

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