#!/usr/bin/env bash
#
# Container entrypoint: runs PocketBase and the TanStack Start site server
# side by side.
#   1. starts PocketBase (data in $PB_DATA_DIR, migrations from ./pb_migrations)
#   2. waits for its health endpoint
#   3. bootstraps the superuser account (idempotent upsert)
#   4. seeds initial content (idempotent, create-if-missing)
#   5. starts the site server
#
# If either process dies the container exits non-zero so Docker restarts it.
set -e

PB_DATA="${PB_DATA_DIR:-/app/pb_data}"
PB_HTTP="${PB_HTTP:-0.0.0.0:8090}"

pb_pid=""
site_pid=""

cleanup() {
  [ -n "$site_pid" ] && kill "$site_pid" 2>/dev/null || true
  [ -n "$pb_pid" ] && kill "$pb_pid" 2>/dev/null || true
  wait 2>/dev/null || true
}
trap cleanup INT TERM

echo "[entrypoint] starting PocketBase…"
./pocketbase serve \
  --http="$PB_HTTP" \
  --dir="$PB_DATA" \
  --migrationsDir=./pb_migrations \
  --publicDir=./pb_public &
pb_pid=$!

echo "[entrypoint] waiting for PocketBase health…"
for _ in $(seq 1 120); do
  if curl -fsS http://127.0.0.1:8090/api/health > /dev/null 2>&1; then
    break
  fi
  sleep 0.5
done

if [ -n "${PB_SUPERUSER_EMAIL:-}" ] && [ -n "${PB_SUPERUSER_PASSWORD:-}" ]; then
  ./pocketbase superuser upsert "$PB_SUPERUSER_EMAIL" "$PB_SUPERUSER_PASSWORD" \
    --dir="$PB_DATA" --migrationsDir=./pb_migrations || true
  echo "[entrypoint] superuser ensured"
  node scripts/seed.mjs || echo "[entrypoint] seed failed (continuing)"
else
  echo "[entrypoint] PB_SUPERUSER_EMAIL/PASSWORD not set — skipping superuser + seed"
fi

echo "[entrypoint] starting site server on :${PORT}…"
node .output/server/index.mjs &
site_pid=$!

set +e
wait -n "$pb_pid" "$site_pid"
exit_code=$?
echo "[entrypoint] a child process exited with code $exit_code — shutting down"
cleanup
exit "$exit_code"
