37 lines
1.1 KiB
Bash
Executable File
37 lines
1.1 KiB
Bash
Executable File
#!/bin/sh
|
|
set -e
|
|
|
|
CREDENTIALS="-h ${PGHOST:-postgres} -U ${PGUSER:-postgres}"
|
|
BACKUP_DIR=${BACKUP_DIR:-/backup}
|
|
RETENTION_DAYS=${RETENTION_DAYS:-7}
|
|
|
|
backup() {
|
|
local filename="backup_$(date +%Y%m%d_%H%M%S).sql.gz"
|
|
echo "[$(date +%Y-%m-%d\ %H:%M:%S)] Starting backup: $filename"
|
|
pg_dumpall $CREDENTIALS | gzip > "$BACKUP_DIR/$filename"
|
|
echo "[$(date +%Y-%m-%d\ %H:%M:%S)] Backup complete: $(du -h "$BACKUP_DIR/$filename" | cut -f1)"
|
|
}
|
|
|
|
cleanup() {
|
|
local count=$(find "$BACKUP_DIR" -name "backup_*.sql.gz" -mtime +$RETENTION_DAYS | wc -l)
|
|
if [ "$count" -gt 0 ]; then
|
|
find "$BACKUP_DIR" -name "backup_*.sql.gz" -mtime +$RETENTION_DAYS -delete
|
|
echo "[$(date +%Y-%m-%d\ %H:%M:%S)] Cleaned up $count backup(s) older than $RETENTION_DAYS days"
|
|
fi
|
|
}
|
|
|
|
# Run immediately on startup
|
|
backup
|
|
cleanup
|
|
|
|
# Schedule: calculate seconds until next 2:00 AM, then run every 24h
|
|
while true; do
|
|
now=$(date +%s)
|
|
target=$(date -d "tomorrow 02:00" +%s)
|
|
sleep_seconds=$((target - now))
|
|
echo "[$(date +%Y-%m-%d\ %H:%M:%S)] Next backup scheduled at $(date -d @$target '+%Y-%m-%d %H:%M:%S')"
|
|
sleep $sleep_seconds
|
|
backup
|
|
cleanup
|
|
done
|