#!/bin/bash # Daily PostgreSQL backup for Spinza (wallet ledger is critical). # Installed on the node by deploy/install-backup.sh as a launchd agent (03:40 daily). set -euo pipefail export PATH="/opt/homebrew/bin:/opt/homebrew/opt/postgresql@17/bin:$PATH" DB="${SPINZA_DB:-spinza}" DEST="${SPINZA_BACKUP_DIR:-$HOME/backups/spinza}" KEEP_DAYS="${SPINZA_BACKUP_KEEP_DAYS:-21}" mkdir -p "$DEST" STAMP=$(date +%Y%m%d-%H%M%S) FILE="$DEST/spinza-$STAMP.dump" pg_dump --format=custom --compress=6 --file="$FILE" "$DB" # Verify the archive lists cleanly (restore test light). pg_restore --list "$FILE" >/dev/null SIZE=$(du -h "$FILE" | cut -f1) echo "$(date -Iseconds) backup ok $FILE ($SIZE)" >>"$DEST/backup.log" # Rotate. find "$DEST" -name 'spinza-*.dump' -mtime +"$KEEP_DAYS" -delete # Monthly full restore test into a scratch database (first day of month). if [ "$(date +%d)" = "01" ]; then dropdb --if-exists spinza_restore_test createdb spinza_restore_test pg_restore --dbname=spinza_restore_test --no-owner "$FILE" ROWS=$(psql -tAqc "select count(*) from credit_transactions" spinza_restore_test) echo "$(date -Iseconds) restore test ok ($ROWS ledger rows)" >>"$DEST/backup.log" dropdb spinza_restore_test fi