Skip to content

Instantly share code, notes, and snippets.

@Alistair1231
Last active October 10, 2024 07:06
Show Gist options
  • Save Alistair1231/b95f7c4a0b2b0e8474297b43675088db to your computer and use it in GitHub Desktop.
Save Alistair1231/b95f7c4a0b2b0e8474297b43675088db to your computer and use it in GitHub Desktop.
restic backup script for docker bind mounts
#!/bin/bash
# to add this as a cronjob that runs every day at 4:00, run `crontab -e` and add the following line:
# 0 4 * * * /srv/restic/run_backup.sh
RESTIC_PATH="/home/al/.nix-profile/bin/restic"
SCRIPT_DIR="/srv/restic"
LOG_FILE="$SCRIPT_DIR/logs/backup_$(date +%Y%m%d_%H%M%S).log"
ENV_FILE="restic.env"
BACKUP_DIR="/srv"
# these directories are excluded from the toggleContainers function
OLD_PROJECTS_DIR="/srv/_old/*"
RESTIC_DIR="/srv/restic/*"
# Function to load environment variables and return the restic command
load_env() {
local env_file="$SCRIPT_DIR/$ENV_FILE"
if [ ! -f "$env_file" ]; then
echo "Error: .env file not found in $SCRIPT_DIR" >&2
return 1
fi
source "$env_file"
if [ -z "$RESTIC_REPOSITORY" ] || [ -z "$RESTIC_PASSWORD" ]; then
echo "Error: RESTIC_REPOSITORY or RESTIC_PASSWORD not set in .env file" >&2
return 1
fi
echo "RESTIC_REPOSITORY='$RESTIC_REPOSITORY' RESTIC_PASSWORD='$RESTIC_PASSWORD' $RESTIC_PATH"
}
# Function to stop or start all containers
toggleContainers() {
if [ "$1" == "stop" ]; then
find "$BACKUP_DIR" -mount -type f -name '*compose.y*ml' -not -path "$RESTIC_DIR" -print0 2>/dev/null |
xargs -0 -I {} sudo docker compose -f "{}" down
return 0
elif [ "$1" == "start" ]; then
find "$BACKUP_DIR" -mount -type f -name '*compose.y*ml' -not -path "$OLD_PROJECTS_DIR" -not -path "$RESTIC_DIR" -print0 2>/dev/null |
xargs -0 -I {} sudo docker compose -f "{}" up -d --remove-orphans
return 0
else
echo "Usage: $0 [start|stop]" >&2
return 1
fi
}
# Function to log messages with timestamps
log() {
echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" | tee -a "$LOG_FILE"
}
# Main execution
main() {
local RESTIC_CMD
RESTIC_CMD=$(load_env)
if [ $? -ne 0 ]; then
log "Error: Failed to load environment. Exiting."
exit 1
fi
log "Stopping all containers"
toggleContainers stop >> "$LOG_FILE" 2>&1
log "Running backup with '--verbose=2 backup \"$BACKUP_DIR\"'"
eval sudo $RESTIC_CMD --verbose=2 backup "$BACKUP_DIR" >> "$LOG_FILE" 2>&1
log "Running cleanup with '--verbose=2 forget --prune --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --keep-yearly 1'"
eval sudo $RESTIC_CMD --verbose=2 forget --prune --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --keep-yearly 1 >> "$LOG_FILE" 2>&1
log "Showing snapshots with '--verbose=2 snapshots'"
eval sudo $RESTIC_CMD --verbose=2 snapshots >> "$LOG_FILE" 2>&1
log "Starting all containers"
toggleContainers start >> "$LOG_FILE" 2>&1
}
# Run the main function
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment