pahvalentines/deploy.sh
michael cae11b95d5 deploy: run alembic migrations after db startup
Wait for database health check then run pending migrations.
Idempotent - only applies migrations not yet in alembic_version.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 07:57:38 -06:00

97 lines
2.4 KiB
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMPOSE_FILE="$ROOT_DIR/backend/docker-compose.yml"
HTDOCS_DIR="/var/vhosts/valentinesong.oliver.digital/htdocs"
if [ ! -d "$ROOT_DIR/.git" ]; then
echo "Error: run this script from the repo root (expected .git here)." >&2
exit 1
fi
if [ ! -f "$COMPOSE_FILE" ]; then
echo "Error: docker compose file not found at $COMPOSE_FILE" >&2
exit 1
fi
if [ ! -d "$HTDOCS_DIR" ]; then
echo "Error: htdocs directory not found at $HTDOCS_DIR" >&2
exit 1
fi
if ! command -v git >/dev/null 2>&1; then
echo "Error: git is required but not found in PATH." >&2
exit 1
fi
if ! command -v docker >/dev/null 2>&1; then
echo "Error: docker is required but not found in PATH." >&2
exit 1
fi
if ! docker compose version >/dev/null 2>&1; then
echo "Error: docker compose is required but not available (docker compose)." >&2
exit 1
fi
echo "Pulling latest code..."
git -C "$ROOT_DIR" pull
echo "Stopping containers..."
docker compose -f "$COMPOSE_FILE" down
echo "Building containers (using cache)..."
docker compose -f "$COMPOSE_FILE" build
echo "Starting containers..."
docker compose -f "$COMPOSE_FILE" up -d --force-recreate
echo "Waiting for database to be healthy..."
MAX_ATTEMPTS=30
ATTEMPT=0
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
if docker compose -f "$COMPOSE_FILE" exec -T db pg_isready -U pah -d pah >/dev/null 2>&1; then
echo "Database is ready."
break
fi
ATTEMPT=$((ATTEMPT + 1))
if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
echo "Error: database did not become healthy after $MAX_ATTEMPTS attempts." >&2
exit 1
fi
echo "Waiting for database... (attempt $ATTEMPT/$MAX_ATTEMPTS)"
sleep 2
done
echo "Running database migrations..."
docker compose -f "$COMPOSE_FILE" exec -T web alembic upgrade head
FRONTEND_ITEMS=(
"index.php"
"waiting.php"
"result.php"
"header.php"
"footer.php"
"opengraph.php"
"admin.html"
"assets"
)
echo "Removing previous frontend files..."
for item in "${FRONTEND_ITEMS[@]}"; do
if [ -e "$HTDOCS_DIR/$item" ]; then
rm -rf "$HTDOCS_DIR/$item"
fi
done
echo "Copying frontend files to htdocs..."
for item in "${FRONTEND_ITEMS[@]}"; do
if [ -e "$ROOT_DIR/$item" ]; then
cp -a "$ROOT_DIR/$item" "$HTDOCS_DIR/"
else
echo "Warning: missing $item in repo, skipping." >&2
fi
done
echo "Deploy complete."