#!/bin/sh
set -eu

config_path="/usr/share/nginx/html/config.js"

require_env() {
  name="$1"
  eval "value=\${$name:-}"
  if [ -z "$value" ]; then
    echo "$name is required when VAULT_ENABLED=true." >&2
    exit 1
  fi
}

read_vault_path() {
  path="$1"
  curl -fsS \
    -H "X-Vault-Token: $VAULT_TOKEN" \
    "$VAULT_ADDR/v1/$VAULT_KV_MOUNT/data/$path" |
    jq -e '.data.data'
}

json_string() {
  jq -Rn --arg value "$1" '$value'
}

if [ "${VAULT_ENABLED:-}" = "true" ]; then
  require_env VAULT_ADDR
  require_env VAULT_TOKEN
  require_env VAULT_KV_MOUNT
  require_env VAULT_SHARED_PATH
  require_env VAULT_PROJECT_PATH

  shared_env="$(read_vault_path "$VAULT_SHARED_PATH")"
  project_env="$(read_vault_path "$VAULT_PROJECT_PATH")"
  runtime_env="$(jq -n --argjson shared "$shared_env" --argjson project "$project_env" '$shared * $project')"

  MAPBOX_ACCESS_TOKEN="$(printf '%s' "$runtime_env" | jq -er '.MAPBOX_ACCESS_TOKEN')"
  MAPBOX_STYLE="$(printf '%s' "$runtime_env" | jq -r '.MAPBOX_STYLE // "mapbox/standard"')"
else
  MAPBOX_ACCESS_TOKEN="${MAPBOX_ACCESS_TOKEN:-}"
  MAPBOX_STYLE="${MAPBOX_STYLE:-mapbox/standard}"
fi

cat >"$config_path" <<EOF
window.__MAPFLOW_CONFIG__ = {
  mapboxAccessToken: $(json_string "$MAPBOX_ACCESS_TOKEN"),
  mapboxStyle: $(json_string "$MAPBOX_STYLE")
};
EOF
