Skip to main content

max / makenotwork

2.2 KB · 70 lines History Blame Raw
1 #!/bin/bash
2 # Makenotwork Database Backup Script
3 # Runs daily via cron, keeps 30 days of backups.
4 #
5 # Setup:
6 # 1. Copy to server:
7 # scp deploy/backup-db.sh root@<server>:/opt/makenotwork/
8 # chmod +x /opt/makenotwork/backup-db.sh
9 #
10 # 2. Create backup directory:
11 # mkdir -p /opt/makenotwork/backups
12 # chown makenotwork:makenotwork /opt/makenotwork/backups
13 #
14 # 3. Add cron job (as makenotwork user):
15 # sudo crontab -u makenotwork -e
16 # # Daily at 03:00 UTC:
17 # 0 3 * * * /opt/makenotwork/backup-db.sh >> /opt/makenotwork/backups/backup.log 2>&1
18
19 set -euo pipefail
20
21 # Configuration
22 BACKUP_DIR="/opt/makenotwork/backups"
23 DB_NAME="makenotwork"
24 DB_USER="makenotwork"
25 RETENTION_DAYS=30
26
27 # Derived
28 TIMESTAMP=$(date +%Y%m%d-%H%M%S)
29 BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}-${TIMESTAMP}.sql.gz"
30
31 echo "[$(date -Iseconds)] Starting backup..."
32
33 # Ensure backup directory exists
34 mkdir -p "$BACKUP_DIR"
35
36 # Dump and compress
37 # Uses peer auth (no password needed when running as makenotwork user)
38 pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"
39
40 # Verify the file is non-empty
41 FILESIZE=$(stat -c%s "$BACKUP_FILE" 2>/dev/null || stat -f%z "$BACKUP_FILE" 2>/dev/null)
42 if [ "$FILESIZE" -lt 100 ]; then
43 echo "[$(date -Iseconds)] ERROR: Backup file suspiciously small (${FILESIZE} bytes)"
44 exit 1
45 fi
46
47 echo "[$(date -Iseconds)] Backup complete: $BACKUP_FILE ($(du -h "$BACKUP_FILE" | cut -f1))"
48
49 # Prune backups older than retention period
50 DELETED=$(find "$BACKUP_DIR" -name "${DB_NAME}-*.sql.gz" -mtime +${RETENTION_DAYS} -delete -print | wc -l)
51 if [ "$DELETED" -gt 0 ]; then
52 echo "[$(date -Iseconds)] Pruned $DELETED backup(s) older than ${RETENTION_DAYS} days"
53 fi
54
55 # Summary
56 TOTAL=$(find "$BACKUP_DIR" -name "${DB_NAME}-*.sql.gz" | wc -l)
57 echo "[$(date -Iseconds)] Total backups on disk: $TOTAL"
58
59 # Sync to offsite host (best-effort — failure here does not fail the backup)
60 SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
61 OFFSITE_SCRIPT="${SCRIPT_DIR}/sync-backup-offsite.sh"
62 if [ -x "$OFFSITE_SCRIPT" ]; then
63 "$OFFSITE_SCRIPT"
64 else
65 # Fallback: check deployed location
66 if [ -x /opt/makenotwork/sync-backup-offsite.sh ]; then
67 /opt/makenotwork/sync-backup-offsite.sh
68 fi
69 fi
70