#!/bin/sh
set -e

# Production migration escape hatch (PR hotfix after PR #1140 cutover):
# legacy rows produced by pre-v2 autonumber listener may no longer
# match the v2 format spec's derived regex (e.g. Contract.ContractNumber
# value "CON-00000694" vs spec "{00000000}"). Strict mode aborts the
# whole seed on any such row, crash-looping every pod. Deploy
# environments opt in to tolerant skip + WARN log by default; CI and
# local dev keep strict behavior (env unset).
export AUTONUMBER_SEED_TOLERATE_LEGACY="${AUTONUMBER_SEED_TOLERATE_LEGACY:-true}"

# Always apply: verify only checks substrate shape, not formula-view usability
# (e.g. views carried over from a TiDB Serverless branch whose DEFINER user no
# longer exists on the new cluster pass verify but fail at read-time with 1356).
# apply is idempotent — it holds an advisory lock and uses CREATE OR REPLACE /
# IF NOT EXISTS throughout — so running it every restart is safe.
echo "Running control-plane apply..."
/usr/local/bin/nexuscrm-setup apply

# Tenant overlay selection and tenant overlay apply are intentionally
# separate controls:
# - NEXUSCRM_TENANT_OVERLAY_DIR selects runtime tenant metadata for server
#   describe/provenance paths. Tenant deployments should set it on every boot.
# - NEXUSCRM_APPLY_TENANT_OVERLAY=1 controls whether this boot mutates the DB
#   by running apply-tenant.
# Greenfield orgs leave both vars unset and get a clean platform baseline.
if [ "${NEXUSCRM_APPLY_TENANT_OVERLAY:-0}" = "1" ]; then
  if [ -z "${NEXUSCRM_TENANT_OVERLAY_DIR:-}" ]; then
    echo "NEXUSCRM_APPLY_TENANT_OVERLAY=1 requires NEXUSCRM_TENANT_OVERLAY_DIR" >&2
    exit 1
  fi
  echo "Running tenant overlay apply..."
  /usr/local/bin/nexuscrm-setup apply-tenant
fi

echo "Starting server..."
exec /usr/local/bin/nexuscrm-server "$@"
