#!/bin/sh
# Runtime entrypoint — fetches secrets from Infisical at every container start.
# Required env (provided by docker-compose env_file=.infisical-mi):
#   INFISICAL_API_URL          e.g. https://infisical.beletage.ro
#   INFISICAL_PROJECT_ID       project workspace id
#   INFISICAL_ENV              env slug (prod / staging / dev)
#   INFISICAL_PATH             secret folder path, e.g. /vreaudigital
#   INFISICAL_CLIENT_ID        Universal Auth client id
#   INFISICAL_CLIENT_SECRET    Universal Auth client secret
#
# All other app secrets (DATABASE_URL, etc.) are fetched at runtime — never baked
# into the image, never written to disk. Rotation in Infisical → restart container.
set -e

if [ -z "$INFISICAL_CLIENT_ID" ] || [ -z "$INFISICAL_CLIENT_SECRET" ]; then
  echo "FATAL: INFISICAL_CLIENT_ID / INFISICAL_CLIENT_SECRET not set" >&2
  echo "  → check that /opt/vreau-digital/.infisical-mi is mounted into the container" >&2
  exit 1
fi

: "${INFISICAL_API_URL:=https://app.infisical.com}"
: "${INFISICAL_ENV:=prod}"
: "${INFISICAL_PATH:=/}"

export INFISICAL_API_URL

INFISICAL_TOKEN=$(infisical login \
  --method=universal-auth \
  --client-id="$INFISICAL_CLIENT_ID" \
  --client-secret="$INFISICAL_CLIENT_SECRET" \
  --silent --plain)

if [ -z "$INFISICAL_TOKEN" ]; then
  echo "FATAL: infisical login returned empty token" >&2
  exit 1
fi
export INFISICAL_TOKEN

# Hand off to the app — secrets injected as env vars by `infisical run`
exec infisical run \
  --projectId="$INFISICAL_PROJECT_ID" \
  --env="$INFISICAL_ENV" \
  --path="$INFISICAL_PATH" \
  --silent \
  -- node dist/server/entry.mjs
