Newer
Older
gnexus-book / scripts / backup-db.sh
#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

on_exit() {
  status=$?
  trap - EXIT
  if [ "$status" -ne 0 ] && [ -n "${SYNAPSE_URL:-}" ] && [ -n "${SYNAPSE_API_KEY:-}" ]; then
    "$SCRIPT_DIR/notify-synapse.sh" \
      "Gnexus Book backup failed" \
      "backup.failed" \
      "backup-db.sh exited with $status on $(hostname)" \
      "high" >/dev/null 2>&1 || true
  fi
  exit "$status"
}
trap on_exit EXIT

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"