#!/bin/sh
# Generate assets/env.js at container start, then hand off to nginx.
#
# Why this exists
# ---------------
# Angular's environment.*.ts files are compiled INTO the bundle, so anything that must
# differ per environment and is not known at build time cannot live there. The SPAs
# already had an assets/env.js for exactly that purpose, but it was a static file
# committed with a hardcoded host:
#
#   window.__env.microfeHost = "https://demo.blu2green.earth/menu/";   # b2g
#   window.__env.microfeHost = "http://192.168.1.58:8080";             # gMarket
#
# Every image therefore shipped one environment's hostname baked in. The b2g image
# deployed to UAT pulled its menu micro-frontend from the PRODUCTION host, and gMarket's
# pointed at an office LAN address unreachable from any browser outside the office.
#
# Writing the file at startup means one image runs in every tier, and the value is set
# by the platform (an ECS task-definition environment variable) rather than by a rebuild.
#
# Values are JSON-encoded defensively: an unquoted or partially quoted value would
# produce a JavaScript syntax error, which in a <script> tag loaded before the app fails
# silently and leaves window.__env undefined.
set -eu

ENV_JS="${SPA_ENV_JS_PATH:-/usr/share/nginx/html/assets/env.js}"
mkdir -p "$(dirname "$ENV_JS")"

# An empty MICROFE_HOST is meaningful: index.html skips injecting the remote
# micro-frontend entirely rather than requesting "/micro-fe.js" from its own origin.
MICROFE_HOST="${MICROFE_HOST:-}"

json_escape() {
    printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
}

cat > "$ENV_JS" <<EOF
// GENERATED AT CONTAINER START by docker/spa-entrypoint.sh - do not edit or commit.
// Set MICROFE_HOST in the ECS task definition to change it; no rebuild is needed.
(function (window) {
  window.__env = window.__env || {};
  window.__env.microfeHost = "$(json_escape "$MICROFE_HOST")";
})(this);
EOF

echo "spa-entrypoint: wrote $ENV_JS with microfeHost=\"${MICROFE_HOST}\"" >&2
if [ -z "$MICROFE_HOST" ]; then
    echo "spa-entrypoint: MICROFE_HOST is empty - the remote micro-frontend will not be injected" >&2
fi

# Cache-bust the env.js reference in index.html.
#
# Why this is needed on top of the nginx no-store rule
# ----------------------------------------------------
# nginx previously served assets/env.js under the generic `expires 7d` rule for *.js.
# Browsers that loaded the app during that window hold a copy of env.js - carrying an old
# microfeHost - for up to a week, and will NOT re-request it just because the server now
# says no-store: the stale entry is still fresh by its original max-age. Those users kept
# pulling the menu micro-frontend from the retired demo host.
#
# Pointing index.html at a URL the browser has never seen sidesteps the stale entry
# outright, so the fix lands on the next page load instead of whenever the old copy
# happens to expire. index.html itself is served without an expires directive, so it
# revalidates against its ETag and picks the new query string up immediately.
#
# The substitution is idempotent - it matches an already-stamped reference too - so a
# container restart re-stamps rather than appending a second query string.
INDEX_HTML="${SPA_INDEX_HTML_PATH:-$(dirname "$(dirname "$ENV_JS")")/index.html}"
if [ -f "$INDEX_HTML" ]; then
    STAMP="$(date -u +%Y%m%d%H%M%S)"
    sed -i "s|assets/env\.js\(?v=[0-9]*\)\{0,1\}|assets/env.js?v=${STAMP}|g" "$INDEX_HTML"
    echo "spa-entrypoint: stamped env.js reference in $INDEX_HTML as ?v=${STAMP}" >&2
else
    echo "spa-entrypoint: WARNING $INDEX_HTML not found - env.js reference not cache-busted" >&2
fi

exec "$@"
