homeserver/backup-db.sh

66 lines
2.2 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# -----------------------------------------------------------------------------
# CONFIGURATION
# -----------------------------------------------------------------------------
# how many days of backups to keep
RETENTION_DAYS=7
# where to store backups
BACKUPDIR=/home/oster/server/backup
# timestamp format for this run
NOW=$(date +'%Y-%m-%d_%H:%M:%S')
# -----------------------------------------------------------------------------
# LOGGING FUNCTION
# -----------------------------------------------------------------------------
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"
}
# -----------------------------------------------------------------------------
# PREPARE
# -----------------------------------------------------------------------------
log "Starting backup run at $NOW"
mkdir -p "$BACKUPDIR"
# -----------------------------------------------------------------------------
# DATABASE BACKUP FUNCTION
# -----------------------------------------------------------------------------
# Usage: backup_db <docker-container-name> <db-username> <output-prefix>
backup_db() {
local container="$1"
local db_user="$2"
local label="$3"
local outfile="${BACKUPDIR}/${NOW}-${label}.sql.gz"
log " Backing up ${label} (container: ${container}, user: ${db_user}) → ${outfile}"
docker exec -t "${container}" \
pg_dumpall --clean --if-exists --username="${db_user}" \
| gzip > "${outfile}"
}
# -----------------------------------------------------------------------------
# RUN THE BACKUPS
# -----------------------------------------------------------------------------
backup_db immich_postgres postgres immich
backup_db authentik-postgresql-1 authentik authentik
backup_db paperless-db-1 paperless paperless
log "All database dumps completed."
# -----------------------------------------------------------------------------
# ROTATE OLD BACKUPS
# -----------------------------------------------------------------------------
log "Removing backups older than ${RETENTION_DAYS} days from ${BACKUPDIR}"
find "${BACKUPDIR}" \
-maxdepth 1 \
-type f \
-name '*.sql.gz' \
-mtime +${RETENTION_DAYS} \
-print -exec rm -f {} \;
log "Backup rotation complete. Exiting."