Repository Public
1#!/bin/bash2# Music SP backup. Run daily (PM2 cron). Two separate parts:3# 1. database — pg_dump (custom format) | AES-256 (openssl, PBKDF2) → $BACKUP_DIR/db/sp-music-YYYYmmdd-HHMMSS.dump.enc (30 days kept)4# 2. library — mirror of the originals and cover art → $BACKUP_DIR/library ; files removed from the library are5# moved to $BACKUP_DIR/trash/<date> and purged after BACKUP_TRASH_DAYS (default 30).6# Renditions and thumbnails are derived data and are not backed up (they are rebuilt from the originals).7# Restore: scripts/restore.sh — see docs/OPERATIONS.md8set -euo pipefail9cd "$(dirname "$0")/.."10if [ -f .env ]; then11 while IFS='=' read -r k v; do12 case "$k" in DATABASE_URL|BACKUP_DIR|BACKUP_PASSPHRASE_FILE|STORAGE_ROOT|BACKUP_TRASH_DAYS)13 v="${v%\"}"; v="${v#\"}"; [ -n "${!k:-}" ] || export "$k=$v" ;;14 esac15 done < .env16fi17: "${DATABASE_URL:?DATABASE_URL missing}"; : "${BACKUP_DIR:?BACKUP_DIR missing}"; : "${BACKUP_PASSPHRASE_FILE:?BACKUP_PASSPHRASE_FILE missing}"; : "${STORAGE_ROOT:?STORAGE_ROOT missing}"18export PATH="/opt/homebrew/opt/postgresql@17/bin:/opt/homebrew/bin:$PATH"19[ -s "$BACKUP_PASSPHRASE_FILE" ] || { echo "passphrase file missing or empty" >&2; exit 1; }20umask 07721mkdir -p "$BACKUP_DIR/db" "$BACKUP_DIR/library" "$BACKUP_DIR/trash"; chmod 700 "$BACKUP_DIR"22stamp="$(date +%Y%m%d-%H%M%S)"2324out="$BACKUP_DIR/db/sp-music-$stamp.dump.enc"25pg_dump --format=custom --no-owner --no-privileges "$DATABASE_URL" | openssl enc -aes-256-cbc -pbkdf2 -iter 200000 -salt -pass "file:$BACKUP_PASSPHRASE_FILE" -out "$out.tmp"26mv "$out.tmp" "$out"27# The archive must decrypt and be readable by pg_restore, otherwise the run fails loudly.28openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 -pass "file:$BACKUP_PASSPHRASE_FILE" -in "$out" | pg_restore --list >/dev/null29/usr/bin/find "$BACKUP_DIR/db" -name 'sp-music-*.dump.enc' -mtime +30 -delete3031for part in originals art; do32 [ -d "$STORAGE_ROOT/$part" ] || continue33 mkdir -p "$BACKUP_DIR/library/$part"34 rsync -a --delete --backup --backup-dir="$BACKUP_DIR/trash/$stamp/$part" --exclude='*.part' "$STORAGE_ROOT/$part/" "$BACKUP_DIR/library/$part/"35done36/usr/bin/find "$BACKUP_DIR/trash" -mindepth 1 -maxdepth 1 -type d -mtime +"${BACKUP_TRASH_DAYS:-30}" -exec rm -rf {} +37rmdir "$BACKUP_DIR/trash/$stamp" 2>/dev/null || true3839files=$(/usr/bin/find "$BACKUP_DIR/library/originals" -type f 2>/dev/null | wc -l | tr -d ' ')40bytes=$(du -sk "$BACKUP_DIR/library" | cut -f1)41printf '{"at":"%s","database":true,"library":true,"files":%s,"bytes":%s}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$files" "$((bytes * 1024))" > "$BACKUP_DIR/last-backup.json.tmp"42mv "$BACKUP_DIR/last-backup.json.tmp" "$BACKUP_DIR/last-backup.json"43echo "backup ok: $out ($(du -h "$out" | cut -f1)), library mirror: $files originals"44