#!/bin/sh set -eu deploy_dir="${1:-.}" backup_dir="${2:-}" if [ -z "$backup_dir" ] || [ ! -d "$backup_dir" ]; then echo "usage: CRANK_RESTORE_CONFIRM=restore scripts/restore-community.sh DEPLOY_DIR BACKUP_DIR" >&2 exit 2 fi if [ "${CRANK_RESTORE_CONFIRM:-}" != "restore" ]; then echo "set CRANK_RESTORE_CONFIRM=restore to confirm destructive restore" >&2 exit 2 fi cd "$deploy_dir" backup_dir="$(cd "$backup_dir" && pwd)" (cd "$backup_dir" && sha256sum --check SHA256SUMS) env_value() { key="$1" default_value="${2:-}" value="$(grep -E "^${key}=" .env | tail -n 1 | cut -d= -f2- || true)" if [ -n "$value" ]; then printf '%s' "$value"; else printf '%s' "$default_value"; fi } cache_backend="$(env_value CRANK_CACHE_BACKEND memory)" compose_profiles="" if [ "$cache_backend" = "valkey" ] || [ "$cache_backend" = "redis" ]; then compose_profiles="--profile cache" fi compose() { # shellcheck disable=SC2086 docker compose $compose_profiles "$@" } compose stop admin-api mcp-server ui postgres_host="$(env_value POSTGRES_HOST)" postgres_port="$(env_value POSTGRES_PORT 5432)" postgres_db="$(env_value POSTGRES_DB crank)" postgres_user="$(env_value POSTGRES_USER crank)" postgres_password="$(env_value POSTGRES_PASSWORD)" docker run --rm --network host \ -e PGPASSWORD="$postgres_password" \ -v "$backup_dir:/backup:ro" \ postgres:16-alpine \ pg_restore --host "$postgres_host" --port "$postgres_port" \ --username "$postgres_user" --dbname "$postgres_db" \ --clean --if-exists --no-owner --no-privileges /backup/postgres.dump admin_container="$(compose ps -aq admin-api)" storage_root="$(env_value CRANK_STORAGE_ROOT /var/lib/crank/storage)" docker run --rm --volumes-from "$admin_container" \ -v "$backup_dir:/backup:ro" alpine:3.21 sh -eu -c \ "find '$storage_root' -mindepth 1 -delete; tar -C '$storage_root' -xzf /backup/artifacts.tar.gz" compose up -d --remove-orphans attempt=1 while [ "$attempt" -le 45 ]; do if curl --fail --silent http://127.0.0.1:3000/ >/dev/null \ && curl --fail --silent http://127.0.0.1:3001/ready >/dev/null \ && curl --fail --silent http://127.0.0.1:3002/ready >/dev/null; then echo "Community state restored from $backup_dir" exit 0 fi sleep 2 attempt=$((attempt + 1)) done compose ps >&2 echo "restored stack failed readiness" >&2 exit 1