#!/bin/sh
# Load runtime configuration from secrets and generate config.js
# This script is called at container startup before nginx starts

set -e

SECRETS_DIR="${SECRETS_DIR:-/run/secrets}"
CONFIG_FILE="/usr/share/nginx/html/config.js"
GOOGLE_MAPS_API_KEY=""
GOOGLE_MAPS_MAP_ID=""

# Try to read Google Maps API key from secret file
if [ -f "$SECRETS_DIR/google-maps-api-key" ]; then
  GOOGLE_MAPS_API_KEY=$(cat "$SECRETS_DIR/google-maps-api-key")
  echo "[Config] Loaded Google Maps API key from $SECRETS_DIR/google-maps-api-key"
else
  echo "[Config] Warning: Google Maps API key not found at $SECRETS_DIR/google-maps-api-key"
  GOOGLE_MAPS_API_KEY=""
fi

# Try to read Google Maps Map ID (optional)
if [ -f "$SECRETS_DIR/google-maps-map-id" ]; then
  GOOGLE_MAPS_MAP_ID=$(cat "$SECRETS_DIR/google-maps-map-id")
  echo "[Config] Loaded Google Maps Map ID from $SECRETS_DIR/google-maps-map-id"
else
  echo "[Config] Info: Google Maps Map ID not found at $SECRETS_DIR/google-maps-map-id (advanced markers require this)"
  GOOGLE_MAPS_MAP_ID=""
fi

# Generate config.js
cat > "$CONFIG_FILE" <<EOF
window.CONFIG = {
  googleMapsApiKey: '$GOOGLE_MAPS_API_KEY',
  googleMapsMapId: '$GOOGLE_MAPS_MAP_ID'
};
EOF

echo "[Config] Generated $CONFIG_FILE"
echo "[Config] Config contents:"
cat "$CONFIG_FILE"
