#!/bin/sh
# Generate nginx config with blazor-environment header
# BLAZOR_ENVIRONMENT defaults to "Staging" if not set
BLAZOR_ENV="${BLAZOR_ENVIRONMENT:-Staging}"

cat > /etc/nginx/conf.d/default.conf <<NGINX_CONF
server {
    listen 80;
    server_name _;
    location / {
        root /usr/share/nginx/html;
        try_files \$uri \$uri/ /index.html;
        add_header blazor-environment $BLAZOR_ENV;
    }
}
NGINX_CONF

# Inject GW_URL into all appsettings JSON files
# This overrides GwUrl regardless of which environment Blazor detects,
# which is critical because the service worker cache strips the
# blazor-environment header and Blazor falls back to Production.
WWWROOT="/usr/share/nginx/html"
if [ -n "$GW_URL" ]; then
  echo "[entrypoint] Setting GwUrl to $GW_URL in all appsettings files"
  for f in "$WWWROOT"/appsettings*.json; do
    [ -f "$f" ] && sed -i "s|\"GwUrl\":\s*\"[^\"]*\"|\"GwUrl\": \"$GW_URL\"|g" "$f"
  done
fi

exec nginx -g 'daemon off;'
