automatic-backup-scripts/backup.sh

82 lines
2.8 KiB
Bash
Executable file

#!/bin/bash
#
#This script will automatically make an encrypted backup to a restic repository as specified with --source
#
#
#
helpFunction()
{
echo ""
echo "Usage: $0 -i INPUT -c CONFIG_DIR -l LOG_DIR"
echo -e "\t-i Input folder that should be backed up."
echo -e "Example:"
echo -e "If you pass -i ~/MyServices/SeRvIce1, then the directory specified in your CONFIG_DIR must contain files service1_repository, service1_password and service1_uuid (note lower case)"
exit 1 # Exit script after printing help
}
while getopts "i:" opt
do
case "$opt" in
i ) INPUT="$OPTARG" ;;
? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
esac
done
# Print helpFunction in case parameters are empty
if [ -z "$INPUT" ] || [ -z "$CONFIG_DIR" ] || [ -z "$LOG_DIR" ] || [ -z "$EXTERNAL_STORAGE_USER" ] || [ -z "$EXTERNAL_STORAGE_URL" ] || [ -z "$EXTERNAL_STORAGE_PORT" ] || [ -z "$EXTERNAL_STORAGE_ROOT_DIR" ] || [ -z "$INTERNAL_STORAGE_ROOT_DIR" ]
then
echo "Some or all of the parameters are empty";
helpFunction
fi
# Begin script in case all parameters are correct
SERVICE=${INPUT##*/}
SERVICE=${SERVICE,,}
DATE=$(date +%Y-%m-%d_%H%M%S)
LOG_FILE="${LOG_DIR}/${SERVICE}_${DATE}.log"
REPOSITORY_FILE="${CONFIG_DIR}/${SERVICE}_repository"
PASSWORD_FILE="${CONFIG_DIR}/${SERVICE}_password"
UUID_FILE="${CONFIG_DIR}/${SERVICE}_uuid"
DOCKER_CONTAINER_FILE="${CONFIG_DIR}/${SERVICE}_container_name"
echo -e "---== START OF BACKUP FOR ${SERVICE^^} - ${DATE} ==---\n\n" > $LOG_FILE
# Stop Docker container
echo -e "### Shutting down container with container name $(<$DOCKER_CONTAINER_FILE)" >> $LOG_FILE
docker container stop $(<$DOCKER_CONTAINER_FILE) >> $LOG_FILE
TRIES=0
while docker ps --filter "name=$(<$DOCKER_CONTAINER_FILE)" --format '{{.ID}}' | grep -q .; do
echo "Waiting for container to stop"
sleep 0.5
((TRIES++))
if [ "$TRIES" -gt 10 ]; then
echo -e "Encountered an error while trying to stop the container. It never stopped..." >> $LOG_FILE
exit 1
fi
done
restic backup $INPUT --verbose --repository-file $REPOSITORY_FILE --password-file $PASSWORD_FILE >> $LOG_FILE
echo -e "\n\n Current snapshots:\n\n" >> $LOG_FILE
restic snapshots --verbose --repository-file $REPOSITORY_FILE --password-file $PASSWORD_FILE >> $LOG_FILE
echo -e "\n\n Health check:\n\n" >> $LOG_FILE
restic check --verbose --repository-file $REPOSITORY_FILE --password-file $PASSWORD_FILE >> $LOG_FILE
echo -e "\n\n Move to external storage:\n\n" >> $LOG_FILE
rsync -rahv --partial --delete-after -e "ssh -p ${EXTERNAL_STORAGE_PORT}" "$(<$REPOSITORY_FILE)/" $EXTERNAL_STORAGE_USER@$EXTERNAL_STORAGE_URL:$EXTERNAL_STORAGE_ROOT_DIR/"$(<$UUID_FILE)" >> $LOG_FILE
# Start Docker container again
echo -e "\n\n Starting container with container name $(<$DOCKER_CONTAINER_FILE)" >> $LOG_FILE
docker container start $(<$DOCKER_CONTAINER_FILE) >> $LOG_FILE