#!/bin/bash
# rebreak-imap-idle Staging — Infisical-Secret-Injection
#
# Wird von pm2 als Script-Interpreter gestartet (ecosystem.config.js).
# Injiziert DATABASE_URL, ADMIN_SECRET, ENCRYPTION_KEY, MS_OAUTH_CLIENT_ID via Infisical-staging.
# ENCRYPTION_KEY muss identisch zum Backend-Key sein (AES-256-GCM).

set -euo pipefail
source /etc/environment

if [[ -z "${INFISICAL_CLIENT_ID:-}" || -z "${INFISICAL_CLIENT_SECRET:-}" ]]; then
  echo "[idle] FEHLER: INFISICAL_CLIENT_ID / INFISICAL_CLIENT_SECRET nicht in /etc/environment gesetzt" >&2
  exit 1
fi

INFISICAL_TOKEN=$(infisical login \
  --method=universal-auth \
  --client-id="${INFISICAL_CLIENT_ID}" \
  --client-secret="${INFISICAL_CLIENT_SECRET}" \
  --silent --plain 2>/dev/null)

[[ -z "$INFISICAL_TOKEN" ]] && { echo "[idle] Infisical login fehlgeschlagen" >&2; exit 1; }

NODE_BIN="/root/.nvm/versions/node/v24.11.1/bin/node"
DAEMON="/srv/rebreak/backend/imap-idle/index.mjs"

exec infisical run \
  --projectId="${INFISICAL_PROJECT_ID:-14b11b35-ef59-4b8a-a16b-398f0cc3ad93}" \
  --env=staging \
  --token="$INFISICAL_TOKEN" \
  -- bash -c '
    set -e
    export DATABASE_URL="${DATABASE_URL:-${NUXT_DATABASE_URL:-}}"
    export ADMIN_SECRET="${ADMIN_SECRET:-${NUXT_ADMIN_SECRET:-}}"
    export ENCRYPTION_KEY="${ENCRYPTION_KEY:-${NUXT_ENCRYPTION_KEY:-}}"
    export BACKEND_URL="http://127.0.0.1:3016"
    export MS_OAUTH_CLIENT_ID="${MS_OAUTH_CLIENT_ID:-}"
    exec '"$NODE_BIN"' '"$DAEMON"'
  '
