#!/bin/sh
set -eu
umask 077

if [ "$#" -ne 1 ]; then
  echo "Usage: AGE_IDENTITY_FILE=/protected/key.txt $0 /absolute/backup.tar.gz.age" >&2
  exit 2
fi
: "${AGE_IDENTITY_FILE:?Set AGE_IDENTITY_FILE to the protected backup identity path}"
backup="$1"
case "$backup" in /*.age) ;; *) echo "Backup path must be absolute and end in .age" >&2; exit 2 ;; esac
[ -f "$backup" ] || { echo "Backup does not exist" >&2; exit 2; }
[ -f "$backup.sha256" ] || { echo "Checksum file does not exist" >&2; exit 2; }
command -v docker >/dev/null
command -v age >/dev/null
command -v sha256sum >/dev/null
command -v openssl >/dev/null
sha256sum --check "$backup.sha256"

temporary="$(mktemp -d "${TMPDIR:-/tmp}/hayva-restore.XXXXXX")"
case "$temporary" in /tmp/hayva-restore.*|*/hayva-restore.*) ;; *) exit 2 ;; esac
container="hayva-restore-$(date -u +%Y%m%d%H%M%S)-$$"
case "$container" in hayva-restore-*) ;; *) exit 2 ;; esac
cleanup() {
  docker rm --force "$container" >/dev/null 2>&1 || true
  rm -rf -- "$temporary"
}
trap cleanup EXIT HUP INT TERM

age --decrypt --identity "$AGE_IDENTITY_FILE" --output "$temporary/payload.tar.gz" "$backup"
tar -C "$temporary" -xzf "$temporary/payload.tar.gz"
grep -q '^schema=hayva-backup-v1$' "$temporary/manifest.txt"
tar -tzf "$temporary/browser-profiles.tar.gz" >/dev/null
tar -tzf "$temporary/computer-artifacts.tar.gz" >/dev/null

restore_password="$(openssl rand -hex 24)"
docker run --detach --name "$container" --network none \
  -e POSTGRES_DB=hayva_restore -e POSTGRES_USER=restore_admin \
  -e POSTGRES_PASSWORD="$restore_password" pgvector/pgvector:0.8.6-pg17 >/dev/null
ready=0
for _attempt in 1 2 3 4 5 6 7 8 9 10 11 12; do
  if docker exec "$container" pg_isready -U restore_admin -d hayva_restore >/dev/null 2>&1; then
    ready=1
    break
  fi
  sleep 2
done
[ "$ready" -eq 1 ] || { echo "Isolated restore database did not become ready" >&2; exit 1; }
docker exec -i "$container" pg_restore --exit-on-error \
  --username restore_admin --dbname hayva_restore < "$temporary/database.dump"
table_count="$(docker exec "$container" psql -At --username restore_admin \
  --dbname hayva_restore -c "SELECT count(*) FROM information_schema.tables WHERE table_schema='public';")"
[ "$table_count" -ge 20 ] || { echo "Restored schema is incomplete" >&2; exit 1; }
docker exec "$container" psql --username restore_admin --dbname hayva_restore \
  -v ON_ERROR_STOP=1 -c "SELECT count(*) AS workspaces FROM workspaces;" \
  -c "SELECT count(*) AS audit_events FROM audit_events;" >/dev/null
printf 'Isolated restore drill passed with %s public tables.\n' "$table_count"
printf 'Record the date, operator, backup identifier, duration, and output in release evidence.\n'
