admin-scripts/backup_borg.sh

107 lines
2.9 KiB
Bash
Executable File

#!/bin/bash
################################################################################
# Backup Borg
# ---------------------------
#
# TODO
#
# Author: Robin Meier - robin@meier.si
################################################################################
# Import logging functionality
script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
logfile=${script_dir}/log/backup.log
log_identifier="BORG"
source ${script_dir}/functions/logging.sh
# Input parameters
BORG_NAME=$1
TIMESTAMP=$2
BORG_DIRS=$3
BORG_OPTS=$4
if [[ -z "$BORG_NAME" || -z "$TIMESTAMP" || -z "$BORG_DIRS" ]]; then
log_echo "[ERROR] Positional parameter missing! (name, timestamp, directories (, borg options))"
exit 40
fi
# Check if required env vars are set
if [[ -z "$BORG_REPO" || -z "$BORG_PASSPHRASE" ]]; then
log_echo "[ERROR] Repo location or passphrase env var missing!"
exit 42
fi
# Automated negative response to these questions
export BORG_RELOCATED_REPO_ACCESS_IS_OK=no
export BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK=no
# Error handling
# trap 'log "Backup interrupted"; exit 2' INT TERM # untested
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
# Output current version
log_echo "Backup borg version: $(borg --version)"
# Create backup
log_echo "Creating backup..."
borg create $BORG_BACKUP_OPTS $BORG_OPTS \
--stats \
--verbose \
--filter AME \
--list \
--show-rc \
--compression lz4 \
--exclude-caches \
::"{hostname}-${BORG_NAME}-${TIMESTAMP}" \
$BORG_DIRS
backup_exit=$?
log_echo "Finished creating backup ($backup_exit)"
# Prune no longer needed backups
log "Pruning backups from repository"
borg prune \
--list \
--glob-archives "{hostname}-${BORG_NAME}-*" \
--show-rc \
--keep-daily 7 \
--keep-weekly 4 \
--keep-monthly 6
prune_exit=$?
log "Finished pruning backups from repository ($prune_exit)"
# Compact repository
log "Compacting repository"
# TODO: Maybe first check if compacting is supported by the client? (Older versions)
borg compact
compact_exit=$?
log "Finished compacting repository ($compact_exit)"
# Calculate global exit code
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
global_exit=$(( compact_exit > global_exit ? compact_exit : global_exit ))
if [ ${global_exit} -eq 0 ]; then
log "Backup, Prune, and Compact finished successfully"
elif [ ${global_exit} -eq 1 ]; then
log_echo "Backup, Prune, and/or Compact finished with warnings"
else
log_echo "Backup, Prune, and/or Compact finished with errors"
fi
log "Backup Finished ($global_exit)"
exit ${global_exit}