#!/bin/sh
# entrypoint.sh — inject environment variables into static HTML before serving.
#
# Reads env vars (EasyPanel env / .env) and replaces placeholders in all
# HTML files under /usr/share/nginx/html using envsubst (nginx:alpine includes it).
#
# Supported variables:
#   GA_ID        — Google Analytics / GTM measurement id (e.g. G-XXXX). Empty = disabled.
#   FORM_EMAIL   — email recipient for FormSubmit contact/RFQ forms.
#   GMAP_LAT/LNG — coords for the free (no-API-key) Google Map embed (type A).
#   GMAP_ZOOM    — map zoom (default 16).
#   GMAP_EMBED   — full embed URL, overrides lat/lng if set.
#
# Any value left empty falls back to sensible defaults (see .env.example).

set -e

HTML_DIR="${HTML_DIR:-/usr/share/nginx/html}"

# --- Build Google Map embed (type A — free, no API key) ---
if [ -z "${GMAP_EMBED:-}" ] && [ -n "${GMAP_LAT:-}" ] && [ -n "${GMAP_LNG:-}" ]; then
    export GMAP_EMBED="https://maps.google.com/maps?q=${GMAP_LAT},${GMAP_LNG}&z=${GMAP_ZOOM:-16}&output=embed"
fi
export GMAP_EMBED="${GMAP_EMBED:-https://maps.google.com/maps?q=13.557229094780995,100.28916297408983&z=16&output=embed}"

# --- Form email default ---
export FORM_EMAIL="${FORM_EMAIL:-mail@mitsuchaiyaporn.com}"

echo "GMAP_EMBED = ${GMAP_EMBED}"
echo "FORM_EMAIL = ${FORM_EMAIL}"
[ -n "${GA_ID:-}" ] && echo "GA_ID      = ${GA_ID} (analytics enabled)" || echo "GA_ID      = (empty — analytics disabled)"

# --- Inject placeholders into every HTML file ---
echo "Injecting env into HTML under ${HTML_DIR}..."
find "${HTML_DIR}" -type f \( -name '*.html' -o -name '*.htm' \) -print0 | while IFS= read -r -d '' f; do
    if grep -q '\${GMAP_EMBED}\|\${FORM_EMAIL}' "$f"; then
        envsubst '${GMAP_EMBED} ${FORM_EMAIL}' < "$f" > "$f.tmp" && mv "$f.tmp" "$f"
    fi
    # GA_ID handled separately (may be removed entirely if empty)
    if grep -q '\${GA_ID}' "$f"; then
        if [ -n "${GA_ID:-}" ]; then
            envsubst '${GA_ID}' < "$f" > "$f.tmp" && mv "$f.tmp" "$f"
        else
            # Remove GA snippet lines (script src + inline gtag init)
            sed -i '/googletagmanager\.com\/gtag\/js/d' "$f"
            sed -i '/window\.dataLayer = window\.dataLayer/d' "$f"
        fi
    fi
done

echo "Entrypoint complete — starting nginx."
exec nginx -g "daemon off;"
