#!/bin/sh
# Hands-On tutorial — React shell startup script.
#
# Two responsibilities:
#  1. Write /tmp/config.json from env vars (the SPA fetches /config.json at boot).
#  2. Inject a tiny inline <script> that pre-seeds localStorage with the OAuth
#     client_id and client_secret so the React shell takes the OAuth code path
#     instead of the broken cookie-fallback path.
#
# Why #2 is necessary:
#   The React shell's shouldUseOauthFlow() checks
#     `localStorage('mib_client_id') && localStorage('mib_client_secret')`
#   — NOT the config.json values directly. On a fresh visit those keys are
#   empty, so the shell falls back to a /auth/login cookie redirect. The
#   only way to reliably ship a setup that "just works" on first visit is
#   to write those keys to localStorage before the React code runs.
#
# Mounted into the React shell container at /scripts/start-react.sh and
# invoked via docker-compose's `command:`.

set -eu

# 1. Write the runtime config (consumed by the SPA on boot).
cat <<EOF > /tmp/config.json
{
  "API_URL": "${API_URL}",
  "AUTH_URL": "${AUTH_URL}",
  "CUSTOM_COMPONENTS_URL": "${CUSTOM_COMPONENTS_URL}",
  "CUSTOM_COMPONENTS_2_URL": "${CUSTOM_COMPONENTS_2_URL}",
  "CUSTOM_COMPONENTS_3_URL": "${CUSTOM_COMPONENTS_3_URL}",
  "AGILE_DELIVERY_COMPONENTS_URL": "${AGILE_DELIVERY_COMPONENTS_URL}",
  "EXTERNAL_EDIT": "${EXTERNAL_EDIT}",
  "MIB_CLIENT_ID": "${MIB_CLIENT_ID}",
  "MIB_CLIENT_SECRET": "${MIB_CLIENT_SECRET}",
  "MIB_CLIENT_REDIRECT_URL": "${MIB_CLIENT_REDIRECT_URL}",
  "BASE_PATH": "${BASE_PATH}",
  "GTM_ID": "${GTM_ID:-}",
  "FROALA_KEY": "${FROALA_KEY:-}",
  "MINIMUM_API_REQUEST_TIME": "${MINIMUM_API_REQUEST_TIME:-}",
  "MOCK_SERVER": "${MOCK_SERVER:-false}"
}
EOF
cp /tmp/config.json /app/config.json

# 2. Restore index.html to its pristine baseline (idempotent across restarts).
if [ -f /app/index.html.orig ]; then
  cp /app/index.html.orig /app/index.html
else
  cp /app/index.html /app/index.html.orig
fi

# 3. Inject a localStorage-seed <script> into <head>.
SEED_SCRIPT="<script nonce='{{CSP_NONCE}}'>localStorage.setItem('mib_client_id','${MIB_CLIENT_ID}');localStorage.setItem('mib_client_secret','${MIB_CLIENT_SECRET}');</script>"
sed -i "s|<head>|<head>$SEED_SCRIPT|" /app/index.html

# 4. Increase nginx header buffers. The default 8K overflows on the OAuth
#    callback (state cookie + correlation cookie + the auth-server's
#    aspnet-core cookies pile up well past 8K), which returns
#    "400 Request Header Or Cookie Too Large" from this nginx.
sed -i '/listen 8080;/a\
  large_client_header_buffers 8 32k;\
  client_header_buffer_size 16k;' /etc/nginx/conf.d/default.conf

# 5. Serve.
exec nginx -g 'daemon off;'
