#!/bin/sh
set -e

# Self-healing schema push:
#   1. Try once — for fresh installs and already-migrated clusters this is all
#      that's needed.
#   2. On failure (typically a Phase 0 upgrade where the new SecretBackend FK
#      can't attach because pre-existing Secret rows reference nothing), run
#      the pre-migrate bootstrap to seed a default SecretBackend + backfill
#      Secret.backendId, then retry.
#   3. If the retry still fails, let the error surface so the pod crashes
#      visibly rather than starting in a half-migrated state.
echo "mcpd: pushing database schema..."
if pnpm -F @mcpctl/db exec prisma db push --schema=prisma/schema.prisma --accept-data-loss 2>&1; then
  :
else
  echo "mcpd: schema push failed — running pre-migrate bootstrap + retrying..."
  node src/db/dist/scripts/pre-migrate-bootstrap.js || true
  pnpm -F @mcpctl/db exec prisma db push --schema=prisma/schema.prisma --accept-data-loss 2>&1
fi

echo "mcpd: seeding templates..."
TEMPLATES_DIR=templates node src/mcpd/dist/seed-runner.js

echo "mcpd: starting server..."
exec node src/mcpd/dist/main.js
