#!/bin/sh
set -eu

RUNTIME_CONFIG_FILE="/usr/share/nginx/html/runtime-config.js"

escape_js_string() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

API_BASE_URL="${ADMIN_API_BASE_URL:-}"
FRONTEND_BASE_URL="${ADMIN_FRONTEND_BASE_URL:-}"
ESCAPED_API_BASE_URL="$(escape_js_string "$API_BASE_URL")"
ESCAPED_FRONTEND_BASE_URL="$(escape_js_string "$FRONTEND_BASE_URL")"

cat > "$RUNTIME_CONFIG_FILE" <<EOF
window.__TERMI_ADMIN_RUNTIME_CONFIG__ = Object.assign(
  {},
  window.__TERMI_ADMIN_RUNTIME_CONFIG__ || {},
  {
    apiBaseUrl: "${ESCAPED_API_BASE_URL}",
    frontendBaseUrl: "${ESCAPED_FRONTEND_BASE_URL}"
  },
)
EOF
