#!/bin/sh
# [doc->REQ-DEP-01] [doc->REQ-DEP-03]
# Source: 05-RESEARCH.md §Pattern 2 + 05-CONTEXT.md D-09
set -e

# Resolve DB path from DATABASE_URL env (strip sqlite: scheme if present).
DB_PATH="${DATABASE_URL:-/data/rebno.db}"

# Map Tigris-injected AWS_* credentials to Litestream's expected env vars.
# fly storage create auto-injects AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY.
# Litestream reads LITESTREAM_ACCESS_KEY_ID / LITESTREAM_SECRET_ACCESS_KEY.
export LITESTREAM_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID:-}"
export LITESTREAM_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY:-}"

# ---- Step 1: Cold restore from Tigris replica (cold start / new volume) ----
if [ ! -f "$DB_PATH" ]; then
  echo "[entrypoint] $DB_PATH missing — restoring from Litestream replica"
  litestream restore -if-replica-exists -o "$DB_PATH" "$DB_PATH" || \
    echo "[entrypoint] no replica found; will start with empty DB"
fi

# ---- Step 2: Pre-migrate snapshot (D-09 safety net) ----
mkdir -p /data/snapshots
if [ -f "$DB_PATH" ]; then
  cp "$DB_PATH" "/data/snapshots/pre-migrate-$(date +%s).db" || true
fi

# ---- Step 3: Run Drizzle migrations (BLOCKING) ----
# Failure → set -e exits non-zero → container crashloop → Fly health check fails → no traffic.
# run-migrations.ts produced by Plan 12; compiled output lands at dist/scripts/run-migrations.js.
echo "[entrypoint] running migrations"
node_modules/.bin/tsx --tsconfig /app/tsconfig.json scripts/run-migrations.ts

# ---- Step 4: Start Litestream replication in background ----
echo "[entrypoint] starting litestream replicate"
litestream replicate -config /etc/litestream.yml &
LITESTREAM_PID=$!

# ---- Step 5: Forward SIGTERM / SIGINT to Litestream (Pitfall 3 mitigation) ----
trap 'echo "[entrypoint] SIGTERM received; stopping litestream"; kill -TERM $LITESTREAM_PID 2>/dev/null; wait $LITESTREAM_PID 2>/dev/null' TERM INT

# ---- Step 6: Exec node — replaces shell PID; dumb-init sends SIGTERM directly to Node ----
# (Pitfall 2 mitigation: exec ensures sigterm.ts grace handler fires within Fly 30s window)
echo "[entrypoint] launching: $@"
exec "$@"
