You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.4 KiB
Bash

#!/bin/bash
# Cronjob needs to be on one line, spaced out for example/ in-case running cronjob from a script that just runs the below
# e.g. 0 0 * * * /home/nathan/scripts/backup/borg/directory_backup.sh \
# -d "/home/nathan/AA/A /home/nathan/AA/C" \
# -b /home/nathan/testBack \
# -r pi2 \
# -R ~/backups/pi1/AA
while getopts d:b:r:R: flag
do
case "${flag}" in
d) DIR=${OPTARG};; # Directory to backup
b) BACKUP_DIR=${OPTARG};; # Where the backup is on local host
r) REMOTE=${OPTARG};; # user@remote or alias (from SSH config), prefer to use alias, as it can deal with port differences
R) REMOTE_DIR=${OPTARG};; # Location of remote backup i.e. /backup/borg/HOSTNAME/docker (then /npm, /vaultwarden, etc.)
esac
done
# As this is using borg, DIR can be passed as "~/dir2 ~/dir2" rather than a single directory
# /var/spool/cron/crontabs # Cron backup
# Function(s)
borg_backup (){
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p $BACKUP_DIR
borg init --encryption=none $BACKUP_DIR
fi
export BORG_REPO=$BACKUP_DIR
borg create ::{hostname}-{now} $DIR
}
borg_prune () {
# Keep last 24 hours of backups, 7 daily backups (one a day/week), 4 weekly (one a week for a month)
borg prune \
--glob-archives '{hostname}-*' \
--keep-hourly 24 \
--keep-daily 7 \
--keep-weekly 4
}
offsite_borg () {
export BORG_REPO=$REMOTE:$REMOTE_DIR
borg create ::{hostname}-{now} $DIR # Backup with of the directory itself (seperate borg repo)
}
offsite_prune () {
# Prune on server, this may take ages though so I'm not sure about this...
# 3 hourly, is hopefully 8 hour intervals of the day
borg prune \
--glob-archives '{hostname}-*' \
--keep-hourly 3 \
--keep-daily 7 \
--keep-weekly 4
}
# Script
# LOCAL
borg_backup
borg_prune # Run prune bash script
# Offsite
if (ssh $REMOTE ls $REMOTE_DIR 2>/dev/null);
then
offsite_borg
else
# Doesn't exist, create, and init repo first
ssh $REMOTE mkdir -p $REMOTE_DIR
borg init --encryption=none $REMOTE:$REMOTE_DIR
offsite_borg
fi
offsite_prune # Seperate, for docker script i.e. backup each container in loop, and prune after ALL containers looped and back up
# so to not keep the containers down for excessively long amounts of time
# OLD backup, where I rsynced an entire rdiff directory from local to offsite
# Create the remote directory for backup if it doesn't exist
# ssh $REMOTE mkdir -p $REMOTE_DIR
# rsync -azh -e ssh \
# --delete \
# $BACKUP_DIR \
# $REMOTE:$REMOTE_DIR