#!/usr/bin/env bash # TowerOps Test Environment Bootstrap # Ensures PostgreSQL is running, test DB exists, and migrations are current. # Run inside or outside of `nix develop` — it works either way. set -e export PATH="/nix/var/nix/profiles/default/bin:$PATH" PROJ_DIR="$(cd "$(dirname "$0")/.." && pwd)" cd "$PROJ_DIR" NIX_CMD="nix develop .#default --command" GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[1;33m' NC='\033[0m' ok() { echo -e "${GREEN}✓${NC} $1"; } fail() { echo -e "${RED}✗${NC} $1"; } info() { echo -e "${YELLOW}→${NC} $1"; } echo "=== TowerOps Test Bootstrap ===" echo "" # --- 1. Check/start PostgreSQL --- info "Checking PostgreSQL..." if pg_isready -h localhost -p 5432 > /dev/null 2>&1; then ok "PostgreSQL is running" else info "PostgreSQL not running — starting services..." $NIX_CMD start-services sleep 2 if pg_isready -h localhost -p 5432 > /dev/null 2>&1; then ok "PostgreSQL started successfully" else fail "Could not start PostgreSQL" exit 1 fi fi # --- 2. Create test database if it doesn't exist --- info "Checking test database..." # Unset DATABASE_URL to avoid the unexpanded $USER issue from nix shell DB_EXISTS=$($NIX_CMD env -u DATABASE_URL bash -c \ "MIX_ENV=test mix ecto.create 2>&1" || true) if echo "$DB_EXISTS" | grep -q "already created"; then ok "Test database already exists" elif echo "$DB_EXISTS" | grep -q "has been created"; then ok "Test database created" else # If it failed for another reason, show the output if echo "$DB_EXISTS" | grep -qi "error"; then fail "Problem with test database:" echo "$DB_EXISTS" exit 1 else ok "Test database ready" fi fi # --- 3. Run pending migrations --- info "Running test migrations..." MIGRATE_OUT=$($NIX_CMD env -u DATABASE_URL bash -c \ "MIX_ENV=test mix ecto.migrate 2>&1" || true) if echo "$MIGRATE_OUT" | grep -q "already up"; then ok "All migrations already applied" elif echo "$MIGRATE_OUT" | grep -qi "migrat"; then ok "Migrations applied" echo "$MIGRATE_OUT" | grep -i "migrat" | head -5 else ok "Migrations up to date" fi # --- 4. Summary --- echo "" echo "=== Status ===" ok "PostgreSQL: running on localhost:5432" ok "Test DB: ready" ok "Migrations: current" echo "" echo "Run tests with: ./tools/dev.sh test" echo " or directly: nix develop --command env -u DATABASE_URL MIX_ENV=test mix test"