#!/bin/bash
set -euo pipefail

DB_URL="${GNEXUS_BOOK_DATABASE_URL:-}"
if [ -z "$DB_URL" ]; then
  echo "GNEXUS_BOOK_DATABASE_URL is required" >&2
  exit 2
fi

DEST="${GNEXUS_BOOK_BACKUP_DIR:-$HOME/NetTera8/service/backups/gnexus-book/db}"
KEEP="${GNEXUS_BOOK_BACKUP_KEEP:-14}"

if [ -z "${GNEXUS_BOOK_BACKUP_DIR:-}" ] && ! mountpoint -q "$HOME/NetTera8"; then
  echo "Off-host mount $HOME/NetTera8 is not available; set GNEXUS_BOOK_BACKUP_DIR explicitly" >&2
  exit 2
fi

mkdir -p "$DEST"
STAMP="$(date +%Y-%m-%d_%H%M%S)"
OUT="$DEST/gnexus_book_$STAMP.dump"
PG_URL="${DB_URL/postgresql+psycopg/postgresql}"

pg_dump --format=custom --no-owner --no-acl --file "$OUT" "$PG_URL"
pg_restore --list "$OUT" > "$OUT.list"
sha256sum "$OUT" > "$OUT.sha256"

mapfile -t dumps < <(ls -1t "$DEST"/gnexus_book_*.dump 2>/dev/null || true)
if [ "${#dumps[@]}" -gt "$KEEP" ]; then
  for old in "${dumps[@]:$KEEP}"; do
    rm -f "$old" "$old.list" "$old.sha256"
  done
fi

echo "$OUT"
