#!/bin/sh
# =============================================================================
# Script Name: borg_backup_hetzner.sh
# Version: 1.2
# Author: Andreas Fleckl
# Description: This script performs backups using Borg to a Hetzner Storage Box.
# It reads directories to backup and exclude from specified files,
# handles logging, performs pruning of old backups, and sends
# notifications about the backup status.
# =============================================================================
# Backup repository location
REPO1="u*@u*.your-storagebox.de:23/./borg"
# Directories to backup
DIR_LIST_FILE="/root/scripts/backup_dirs.txt"
if [ ! -f "$DIR_LIST_FILE" ]; then
echo "Directory list file not found: $DIR_LIST_FILE"
exit 1
fi
BACKUP_DIRS=$(cat "$DIR_LIST_FILE" | xargs)
echo "Directories to be backed up: '$BACKUP_DIRS'"
# File containing the list of directories to exclude
EXCLUDE_FILE="/root/scripts/exclude_dirs.txt"
if [ ! -f "$EXCLUDE_FILE" ]; then
echo "Exclude file not found: $EXCLUDE_FILE"
exit 1
fi
EXCLUDES=$(awk '{print "--exclude " $0}' "$EXCLUDE_FILE" | xargs)
# Log file location
LOG="/var/log/borg_backup.log"
# Function to log messages
log_message() {
echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" | tee -a "$LOG"
}
# Function to send notification email
send_notification() {
local SUBJECT=$1
local MESSAGE=$2
echo "$MESSAGE" | mail -s "$SUBJECT" you@example.com
}
# Ensure BORG_PASSPHRASE is set in the environment or use a secure method to source it
if [ -z "$BORG_PASSPHRASE" ]; then
log_message "BORG_PASSPHRASE is not set. Please export it securely."
exit 1
fi
log_message "Starting backup process."
# Creating backup of specified directories
log_message "Starting backup of directories: $BACKUP_DIRS"
if borg create --progress --lock-wait 10 --read-special $EXCLUDES "$REPO1::'{hostname}-{now:%Y-%m-%d}'" $BACKUP_DIRS; then
log_message "Backup completed successfully."
send_notification "Borg Backup Successful" "Backup completed successfully for $BACKUP_DIRS."
else
log_message "Error during backup creation."
send_notification "Borg Backup Failed" "Error during backup creation for $BACKUP_DIRS."
exit 1
fi
# Pruning old backups
log_message "Starting pruning of old backups"
if borg prune -v --list "$REPO1" --keep-daily=7 --keep-weekly=4 --keep-monthly=6; then
log_message "Pruning completed successfully."
send_notification "Borg Pruning Successful" "Pruning completed successfully."
else
log_message "Error during pruning."
send_notification "Borg Pruning Failed" "Error during pruning."
exit 1
fi
log_message "Borg backup process completed."