#!/usr/bin/env bash
set -euo pipefail
log() { echo "$(date -Is) [restore] $*"; }
die() { log "FATAL: $*"; exit 1; }
mode="${1:-}"; artifact="${2:-}"
shift 2 2>/dev/null || true
[ -n "$mode" ] && [ -n "$artifact" ] || die "usage: restore.sh {repos|db} <artifact> [opts]"
[ -f "$artifact" ] || die "artifact not found: $artifact"
case "$mode" in
repos)
dest="/tmp/gluecron-restore-$(date +%s)"
while [ $# -gt 0 ]; do case "$1" in --dest) dest="$2"; shift 2;; *) shift;; esac; done
mkdir -p "$dest"
tar -xzf "$artifact" -C "$dest"
log "extracted repos snapshot into: $dest"
log "verify a repo, e.g.: git -C \"$dest\"/repos/<owner>/<name>.git log -1"
log "when satisfied, swap into place by stopping gluecron and rsync-ing over \$GIT_REPOS_PATH"
;;
db)
target="${SCRATCH_DATABASE_URL:-}"
while [ $# -gt 0 ]; do case "$1" in --target-url) target="$2"; shift 2;; *) shift;; esac; done
[ -n "$target" ] || die "no target: pass --target-url or set SCRATCH_DATABASE_URL (refusing to guess prod)"
log "restoring $artifact into $target"
pg_restore --clean --if-exists --no-owner --no-privileges --dbname "$target" "$artifact"
log "restore complete. sanity-check: psql \"$target\" -c 'select count(*) from users;'"
;;
*)
die "unknown mode '$mode' (want: repos | db)"
;;
esac
|