#!/bin/sh # bootstrap.sh — the federatedcomputer/superbrain-migrate entrypoint. # # Makes fresh-install and upgrade the SAME command, so a server never needs # the source tree: # 1. wait for PostgreSQL, # 2. if the database has no tables, apply /db/schema.sql AS DB_USER # (object ownership matters: every later migration must be able to # ALTER these objects — applying as postgres would strand ownership), # 3. always run /db/migrate.sh (ordered, checksummed, advisory-locked, # one transaction per file; idempotent against a bootstrapped schema). # # Environment (same contract as migrate.sh): # PGPASSWORD required # DB_HOST default "db" # DB_USER default "superbrain" # DB_NAME default "superbrain" set -eu DB_HOST="${DB_HOST:-db}" DB_USER="${DB_USER:-superbrain}" DB_NAME="${DB_NAME:-superbrain}" [ -n "${PGPASSWORD:-}" ] || { echo "bootstrap: PGPASSWORD is required" >&2; exit 1; } psql() { command psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -v ON_ERROR_STOP=1 "$@"; } echo "bootstrap: waiting for postgres at $DB_HOST" i=0 until pg_isready -q -h "$DB_HOST" -U "$DB_USER" 2>/dev/null; do i=$((i + 1)) [ "$i" -ge 60 ] && { echo "bootstrap: postgres at $DB_HOST never became ready" >&2; exit 1; } sleep 2 done TABLES=$(psql -t -A -c "SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'") if [ "$TABLES" = "0" ]; then echo "bootstrap: empty database '$DB_NAME' - applying schema.sql as $DB_USER" psql -q -f /db/schema.sql else echo "bootstrap: database has $TABLES tables - skipping schema.sql" fi exec sh /db/migrate.sh