#!/usr/bin/env bash
# build-prod.sh — Prod build: build server image, start postgres, run migrations, tear down
set -euo pipefail

REPO_DIR="$(cd "$(dirname "$0")/.." && pwd)"

echo "=== Building server image ==="
podman build -t splint -f "$REPO_DIR/compose/server.Containerfile" "$REPO_DIR"

echo "=== Pulling Postgres image ==="
podman pull docker.io/library/postgres:17-alpine

echo "=== Starting Postgres (prod) ==="
podman compose -f "$REPO_DIR/compose/compose.prod.yml" up -d postgres

echo "=== Waiting for Postgres to be ready ==="
for i in $(seq 1 30); do
    if podman exec splint-postgres pg_isready -U splint >/dev/null 2>&1; then
        echo "Postgres is ready."
        break
    fi
    echo "  waiting... ($i/30)"
    sleep 1
done

echo "=== Running migrations ==="
podman compose -f "$REPO_DIR/compose/compose.prod.yml" run --rm server \
    sh -c "cd /app/packages/server && bunx drizzle-kit migrate"

echo "=== Stopping Postgres ==="
podman compose -f "$REPO_DIR/compose/compose.prod.yml" down

echo "=== Build (prod) complete ==="
