#!/usr/bin/env sh # Restore a gzip SQL backup (same format as scripts/backup-postgres.sh) into the # local Docker database. Use --reset to wipe the local volume first (recommended # for a clean clone). Does not contact production. # # Usage: # cp docker-compose.override.local.example docker-compose.override.yml # once # docker compose up -d database # ./scripts/restore-postgres-local.sh --reset [path/to/dashboard_db-*.sql.gz] # # If you omit the file path, the newest ./backups/dashboard_db-*.sql.gz is used. set -e SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) PROJECT_ROOT=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd) cd "$PROJECT_ROOT" RESET=0 BACKUP_FILE= for arg in "$@"; do case "$arg" in --reset) RESET=1 ;; -*) echo "Unknown option: $arg"; exit 1 ;; *) BACKUP_FILE=$arg ;; esac done if [ -z "$BACKUP_FILE" ]; then BACKUP_FILE=$(ls -t "$PROJECT_ROOT"/backups/dashboard_db-*.sql.gz 2>/dev/null | head -1) fi if [ -z "$BACKUP_FILE" ] || [ ! -f "$BACKUP_FILE" ]; then echo "No backup file found. Run ./scripts/fetch-prod-db.sh or pass a .sql.gz path." exit 1 fi BACKUP_FILE=$(CDPATH= cd -- "$(dirname -- "$BACKUP_FILE")" && pwd)/$(basename -- "$BACKUP_FILE") if [ "$RESET" != 1 ]; then echo "Refusing to restore without --reset (avoids a messy mix of old + dump data)." echo "Run: $0 --reset \"$BACKUP_FILE\"" exit 1 fi echo "Stopping stack and removing LOCAL Docker volumes for this project..." docker compose down -v echo "Starting database..." docker compose up -d database echo "Waiting for Postgres (TCP on 127.0.0.1:5432 inside container)..." i=0 while [ "$i" -lt 90 ]; do if docker compose exec -T database sh -c 'pg_isready -h 127.0.0.1 -p 5432 -U "$POSTGRES_USER" -d "$POSTGRES_DB"' >/dev/null 2>&1; then break fi i=$((i + 1)) sleep 1 done if [ "$i" -eq 90 ]; then echo "Database did not become ready in time." exit 1 fi echo "Restoring from $BACKUP_FILE ..." # Use Unix socket (no -h): matches pg_isready-without-TCP race on Docker Desktop; avoids connection refused to 127.0.0.1 gunzip -c "$BACKUP_FILE" | docker compose exec -T database sh -c \ 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1' echo "Local database restored. Use DB_HOST=127.0.0.1 DB_PORT=5432 (with override) in .env for development." echo "Do not point these credentials at production."