#!/bin/sh
# Hands-On tutorial — BFF startup script.
#
# What it does: trust the self-signed localtest.me cert system-wide before
# launching the .NET BFF. Without this, the BFF cannot validate JWTs (it
# fetches the JWKS keys from https://auth.localtest.me/.well-known/...),
# which makes EVERY /api request fail with 401, and triggers a thread-race
# condition on `JwtBearerOptions.TokenValidationParameters.PropertyBag`:
#
#   System.ArgumentException: An item with the same key has already been
#   added. Key: TraceIdentifier
#
# That error looks like a code bug in MibServer3 — it isn't. It's a
# downstream symptom of "JWT validation failing under concurrent requests".
# Trust the cert and the symptom disappears.
#
# Mounted into the BFF container at /scripts/start-frontend-with-local-ca.sh
# and invoked via docker-compose's `entrypoint:`.

set -eu

CERT_SOURCE="/app/local-certs/localtest.me.crt"
CERT_TARGET="/usr/local/share/ca-certificates/localtest.me.crt"

if [ -f "${CERT_SOURCE}" ] && command -v update-ca-certificates >/dev/null 2>&1; then
  cp "${CERT_SOURCE}" "${CERT_TARGET}"
  update-ca-certificates >/tmp/update-ca-certificates.log 2>&1 || cat /tmp/update-ca-certificates.log
fi

exec dotnet MediaiBox.Cms.FrontEnd.Server.dll
