#!/bin/sh
# Don't use set -e to avoid crashing if chown fails

# Generate env.js from API_BASE environment variable
# This is set in the Helm deployment values
TARGET="/usr/share/nginx/html/env.js"

# API_BASE should be set via deployment env (e.g., from Helm values)
# Default to /api as fallback (relative path)
: ${API_BASE:=/api}

echo "[ENTRYPOINT] Generating env.js with API_BASE=${API_BASE}"

cat > "$TARGET" <<EOF
window.__ENV__ = {
  API_BASE: "${API_BASE}"
};
EOF

if [ -f "$TARGET" ]; then
  echo "[ENTRYPOINT] ✓ env.js generated successfully at $TARGET"
  cat "$TARGET"
else
  echo "[ENTRYPOINT] ✗ Failed to generate env.js"
  exit 1
fi

# Ensure ownership/permissions for nginx (don't fail if this doesn't work)
chown nginx:nginx /usr/share/nginx/html/env.js 2>/dev/null || echo "[ENTRYPOINT] Note: Could not change ownership (not critical)"

echo "[ENTRYPOINT] env.js setup complete"
