2024-08-04 23:10:36 +02:00
#!/bin/bash
SCRIPT_ABS_LOCATION = $( realpath " $( dirname " ${ 0 } " ) " )
2024-12-29 15:08:09 +01:00
source " $SCRIPT_ABS_LOCATION /duplicati-backup.env "
source " $SCRIPT_ABS_LOCATION /../logger.sh "
2024-08-04 23:10:36 +02:00
SOURCE_DIR = "/mnt/data/duplicati"
# Set default values for parameters
MAX_BACKUPS = 7
BACKUP_FOLDER = ""
# Override default values with command-line arguments
while getopts ":f:h:u:p:m:b:" opt; do
case $opt in
f) SOURCE_DIR = " $OPTARG " ; ;
h) SSH_DESTINATION = " $OPTARG " ; ;
u) SSH_USERNAME = " $OPTARG " ; ;
2024-12-29 15:08:09 +01:00
p) SSH_KEY = " $OPTARG " ; ;
2024-08-04 23:10:36 +02:00
m) MAX_BACKUPS = " $OPTARG " ; ;
b) BACKUP_FOLDER = " $OPTARG " ; ;
\? ) echo " Invalid option: - $OPTARG " ; exit 1; ;
esac
done
# Create a temporary file for the encrypted archive
2024-12-29 15:08:09 +01:00
# shellcheck disable=SC2015
2024-08-04 23:10:36 +02:00
TMP_FILENAME = duplicati_db-$( date +"%Y%m%d" ) .bak &&
2024-12-29 15:08:09 +01:00
TMP_FILEPATH = " $SCRIPT_ABS_LOCATION " || { log "Error: Failed to create a temporary file." ; exit 1; }
2024-08-04 23:10:36 +02:00
# Create the encrypted archive using tar and openssl
log "Compressing and excrypting the Duplicati Databases"
2024-12-29 15:08:09 +01:00
sudo tar -czf - " $SOURCE_DIR " | openssl enc -aes-256-cbc -pbkdf2 -pass " pass: $BACKUP_ENCR_PASSPHRASE " > " $TMP_FILEPATH / $TMP_FILENAME " || { log "Error: Failed to create encrypted archive." ; exit 1; }
2024-08-04 23:10:36 +02:00
# Connect to the backup host and count the number of existing backups
log "Fetching number of backups in destination folder"
2024-12-29 15:08:09 +01:00
EXISTING_BACKUPS = $( ssh " $SSH_USERNAME @ $SSH_DESTINATION " -p 23 -i " $SSH_KEY ls " | sudo wc -l) || { log "Error: Failed to count existing backups." ; exit 1; }
2024-08-04 23:10:36 +02:00
# Remove old backups if there are too many
2024-12-29 15:08:09 +01:00
if ( ( EXISTING_BACKUPS > MAX_BACKUPS ) ) ; then
2024-08-04 23:10:36 +02:00
log "Removing old backups in order to save space"
2024-12-29 15:08:09 +01:00
ssh " $SSH_USERNAME @ $SSH_DESTINATION " -p 23 -i " $SSH_KEY ls -t $BACKUP_FOLDER | tail -n + $(( MAX_BACKUPS+1)) | xargs rm " || { log "Error: Failed to remove old backups." ; exit 1; }
2024-08-04 23:10:36 +02:00
fi
# Transfer the encrypted archive to the backup host using scp
log "Transfering archive to SSH Destination"
scp -v -P 23 -i " $SSH_KEY " " $TMP_FILEPATH / $TMP_FILENAME " " $SSH_USERNAME @ $SSH_DESTINATION : $BACKUP_FOLDER $TMP_FILENAME " || { log "Error: Failed to transfer the encrypted archive." ; exit 1; }
# Remove the temporary file
log "Cleaning up files"
rm " $TMP_FILEPATH / $TMP_FILENAME " || { log "Error: Failed to remove the temporary file." ; exit 1; }
log "Backup completed successfully."