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.

78 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 8 hours of backups, last 3 days, and last 2 weeks. LESS for local to save storage
borg prune \
--glob-archives '{hostname}-*' \
--keep-hourly 8 \
--keep-daily 3 \
--keep-weekly 2
# Then compact (actually clear up the disk space of the files removed via prune)
borg compact
}
offsite_borg () {
export BORG_REPO=$REMOTE:$REMOTE_DIR
borg create ::{hostname}-{now} $DIR # Backup with of the directory itself (seperate borg repo)
}
offsite_prune () {
export BORG_REPO=$REMOTE:$REMOTE_DIR
# Prune on server, this may take ages though so I'm not sure about this...
borg prune \
--glob-archives '{hostname}-*' \
--keep-hourly 24 \
--keep-daily 7 \
--keep-weekly 4 \
--keep-monthly 3
# Then compact (actually clear up the disk space of the files removed via prune)
borg compact
}
# 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