#!/usr/bin/env bash
set -uo pipefail
BACKUP_DIR="/opt/gluecron/backups"
APP_CONTAINER="gluecron-gluecron-1"
PG_IMAGE="postgres:17-alpine"
DRILL="gluecron-restore-drill-$$"
log() { echo "$(date -Is) [drill] $*"; }
cleanup() { docker rm -f "$DRILL" >/dev/null 2>&1 || true; }
trap cleanup EXIT
dump="$(ls -t "$BACKUP_DIR"/gluecron-db-*.dump 2>/dev/null | head -1)"
if [ -z "$dump" ]; then
log "FAIL: no backup found in $BACKUP_DIR"
exit 1
fi
log "restoring: $dump"
raw_url="$(docker exec "$APP_CONTAINER" printenv DATABASE_URL)"
clean_url="${raw_url%%DATABASE_URL=*}"
docker run -d --name "$DRILL" -e POSTGRES_PASSWORD=drill -e POSTGRES_DB=drill \
"$PG_IMAGE" >/dev/null
for _ in $(seq 1 30); do
docker exec "$DRILL" pg_isready -U postgres -d drill >/dev/null 2>&1 && break
sleep 1
done
docker cp "$dump" "$DRILL":/tmp/d.dump
docker exec "$DRILL" pg_restore --no-owner --no-privileges -U postgres -d drill /tmp/d.dump \
>/dev/null 2>&1 || true
fails=0
checked=0
for tbl in users repositories issues pull_requests oauth_apps; do
restored="$(docker exec "$DRILL" psql -At -U postgres -d drill \
-c "SELECT count(*) FROM $tbl" 2>/dev/null | tr -d '[:space:]')"
live="$(docker run --rm -e U="$clean_url" -e TBL="$tbl" "$PG_IMAGE" \
sh -c 'psql -At "$U" -c "SELECT count(*) FROM $TBL"' 2>/dev/null | tr -d '[:space:]')"
if [ -z "$restored" ] || [ -z "$live" ]; then
log "WARN: $tbl — could not read a count (restored='$restored' live='$live')"
fails=$((fails + 1))
continue
fi
checked=$((checked + 1))
if [ "$restored" = "$live" ]; then
log "OK $tbl: $restored rows (matches live)"
else
log "FAIL $tbl: restored=$restored live=$live (MISMATCH)"
fails=$((fails + 1))
fi
done
if [ "$checked" -eq 0 ]; then
log "FAIL: could not verify any table"
exit 1
fi
if [ "$fails" -ne 0 ]; then
log "FAIL: $fails check(s) failed — backup is NOT trustworthy"
exit 1
fi
echo "$(date +%s)" > "$BACKUP_DIR/.last-restore-drill-ok"
log "PASS: restore verified against live Neon ($checked tables). Backup is good."
|