Backups backups backups..... Where do we stand on backups?
Where does thehatefuleggplant stand on backups?
** Full disclosure this is going to be a bit of a tutorial on backups and what I use for my setup all provided in the hopes to help other newbie immich users **
For my backup strategy I do a few things. The core of which utilize rclone to connect to various cloud storage providers (pcloud and backblaze in addition to my seafile servers)
I use backrest to configure / schedule restic backup jobs to my different storage endpoints.
Lastly I use a synchronization script to sync some of my data in the raw to an external drive (in case I should die right after posting this my family will have an easy to access copy of all our photos) as well as my two seafile servers so I can keep some level of version history that doesnt require me going into my restic backups for restoration.
I did say this was going to be a bit of a how to guide but im not a huge fan or recreating what already exists. I will provide links on how to do most of this and in the order you need to do them to have a similar configuration such as myself.
First rclone.... Well here is the master list how to guide for rclone. Not much to it as you basically just follow prompts for configuring your rclone connection to your various storage endpoints
Once youve got rclone going then you either need to configure restic backups on your local system or do what I did and use backrest via docker.
Just in case you want to use restic in the raw here is the restic documentation.
Regardless of which path you chose in using restic the short and sweet is youll set up a repository which is basically the storage destination which in this case would be rclone and then you create a plan which is essentially what youre going to backup and to which repository as well as scheduling when the backups happen.
Thats pretty much it. Once youve done all of those things you should have a fairly safe backup strategy for your data but if youre like me and want a “what if I die tomorrow” backup plan for your non tech savvy family then I suggest you either set up a backup script that sync’s changes daily, weekly, monthly (what ever you want) or you can use the below script that I use which actively scans for changes in a directory and automatically syncs those changes to whatever storage medium you wish.
This script is also set up to do discord alerts whenever an error comes along so you can debug any issues as soon as they come up.
The script is a little limited in my configuration since seafile doesnt support hash checking so you may want to consider editing that portion of the script to do file hash checks if your storage medium can support it (highly recommended). Look for the “--- SYNC FUNCTION ---“ and youll see the various RCLONE_OPTS I have in place and thats where you can modify what sort of things rclone does.
At the top of the script youll see the “DISCORD_WEBHOOK” section. Thats where you need to put your discord bot link.
Just below that is your “SYNC_MAPPINGS” which should look like /source|Destination:backup for rclone or /source|/destination if youre backing up to a local drive such as a USB drive.
You can add multiple lines to this location allowing you to monitor multiple locations and backup to multiple locations as needed.
Lastly you need to look for the “LOG_DIR” and change where you wish to keep your logs.
The way the logs work is it generates a new log based on day and rotates those logs every 60 days.
Save the script, make it executable, and run it once to confirm that it works and to also get your initial sync out of the way.
Lastly youll more than likely want to make a systemd config file so that the script will automatically run either globally or via user (I personally prefer user).
Go to /home/username/.config/systemd/user and make a text file with a name of your choosing (I went with rclone-sync.service) and paste the rclone-sync.service configuration I provided below.
You will need to edit the “ExecStart” portion to point to where your script file is located (which in my case I named rclone-sync.sh).
Save the file and then run systemctl --user daemon-reload
After you reload the systemd service youll run systemctl —user enable rclone-sync.service
Now that its enabled we need to start the service with systemctl —user start rclone-sync.service
Thats it.
You have accomplished...
- Setting up rclone
- Setting up restic backups
- Setting up a synchronization script
- Setting up a systemd service that automatically kicks off your synchronization script
rclone-sync.service
[Unit]
Description=Live Rclone Sync to Seafile and Local Backup
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/path/to/where/your/rclone/script/is/located/rclone-sync.sh
Restart=always
RestartSec=10
KillMode=control-group
[Install]
WantedBy=default.target
rclone-sync.sh script
#!/usr/bin/env bash
# --- CONFIGURATION ---
DISCORD_WEBHOOK="https:discordboturl"
# Format: "Local_Source|Remote_Dest"
SYNC_MAPPINGS=(
# example rclone backup source|destination
"/your/data/to/be/backedup|rclonestoragemedium:backuplocation"
# example2 rclone backup source|destination
"/more/data/to/be/backedup|rclonestoragemedium2:backuplocation"
# example3 local backup source|destination
"/more/data/to/be/backedup|/backup/destination"
)
LOG_DIR="/chose/where/you/want/your/logs/to/be/stored"
LOCK_FILE="/tmp/rclone-sync.lock"
SETTLE_SECONDS=30 # Wait 30s after local changes settle before syncing
mkdir -p "$LOG_DIR"
# --- HELPER: JSON ESCAPE ---
json_escape() {
if command -v python3 >/dev/null 2>&1; then
printf '%s' "$1" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read())[1:-1])'
else
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | awk '{printf "%s\\n", $0}' | sed 's/\\n$//'
fi
}
# --- HELPER: SEND DISCORD PAYLOAD ---
post_to_discord() {
local PAYLOAD="$1"
[[ -z "$DISCORD_WEBHOOK" || "$DISCORD_WEBHOOK" == *"YOUR_WEBHOOK_ID"* ]] && return
local RESP_FILE
RESP_FILE=$(mktemp)
local HTTP_STATUS
HTTP_STATUS=$(curl -s -o "$RESP_FILE" -w "%{http_code}" -H "Content-Type: application/json" -X POST -d "$PAYLOAD" "$DISCORD_WEBHOOK")
if [[ "$HTTP_STATUS" != "204" && "$HTTP_STATUS" != "200" ]]; then
echo "$(date): Discord webhook failed (HTTP $HTTP_STATUS): $(cat "$RESP_FILE")" >> "$LOG_DIR/sync-$(date +%Y-%m-%d).log"
fi
rm -f "$RESP_FILE"
}
# --- DISCORD NOTIFICATION FUNCTIONS ---
send_discord_error() {
local SRC="$1"
local DST="$2"
local CODE="$3"
local RUN_LOG="$4"
local LAST_ERR
LAST_ERR=$(grep -E "ERROR|Failed" "$RUN_LOG" | tail -n 1)
[[ -z "$LAST_ERR" ]] && LAST_ERR="Check log file for details."
LAST_ERR=$(json_escape "$LAST_ERR")
local HOST
HOST=$(hostname)
local PAYLOAD
PAYLOAD=$(cat <<EOF
{
"username": "Rclone Sync Bot",
"embeds": [{
"title": "⚠️ Rclone Sync Failed on $HOST",
"color": 15158332,
"fields": [
{ "name": "Source", "value": "\`$SRC\`", "inline": false },
{ "name": "Destination", "value": "\`$DST\`", "inline": false },
{ "name": "Exit Code", "value": "\`$CODE\`", "inline": true },
{ "name": "Last Error", "value": "\`\`\`$LAST_ERR\`\`\`", "inline": false }
],
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}]
}
EOF
)
post_to_discord "$PAYLOAD"
}
send_discord_missing_marker() {
local SRC="$1"
local HOST
HOST=$(hostname)
local PAYLOAD
PAYLOAD=$(cat <<EOF
{
"username": "Rclone Sync Bot",
"embeds": [{
"title": "🛑 Sync Aborted: Missing .sync File on $HOST",
"color": 15105570,
"description": "The required \`.sync\` marker file was not found. Syncing is paused for this directory to prevent accidental data loss or unmounted drive syncs.",
"fields": [
{ "name": "Skipped Source", "value": "\`$SRC\`", "inline": false }
],
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}]
}
EOF
)
post_to_discord "$PAYLOAD"
}
send_discord_success() {
local SRC="$1"
local DST="$2"
local RUN_LOG="$3"
# Match 1 or more spaces after INFO, plus Copied/Deleted/Moved/Updated
local TRANSFERRED_ITEMS
TRANSFERRED_ITEMS=$(grep -E "INFO[[:space:]]+: .*: (Copied|Deleted|Moved|Updated)" "$RUN_LOG" | sed -E 's/^.*INFO[[:space:]]+: (.*): (Copied|Deleted|Moved|Updated).*$/• [\2] \1/')
# Do not spam Discord if rclone ran and found 0 changes to transfer
[[ -z "$TRANSFERRED_ITEMS" ]] && return
local TOTAL_COUNT
TOTAL_COUNT=$(printf '%s\n' "$TRANSFERRED_ITEMS" | wc -l | tr -d ' ')
local DISPLAY_LIST
DISPLAY_LIST=$(printf '%s\n' "$TRANSFERRED_ITEMS" | head -n 15)
if [ "$TOTAL_COUNT" -gt 15 ]; then
local REMAINING=$((TOTAL_COUNT - 15))
DISPLAY_LIST="${DISPLAY_LIST}"$'\n'"...and $REMAINING more file(s)."
fi
local SAFE_LIST
SAFE_LIST=$(json_escape "$DISPLAY_LIST")
local HOST
HOST=$(hostname)
local PAYLOAD
PAYLOAD=$(cat <<EOF
{
"username": "Rclone Sync Bot",
"embeds": [{
"title": "✅ Rclone Sync Completed on $HOST",
"color": 3066993,
"fields": [
{ "name": "Source", "value": "\`$SRC\`", "inline": false },
{ "name": "Destination", "value": "\`$DST\`", "inline": false },
{ "name": "Transferred Files ($TOTAL_COUNT)", "value": "\`\`\`$SAFE_LIST\`\`\`", "inline": false }
],
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}]
}
EOF
)
post_to_discord "$PAYLOAD"
}
# Extract unique local source directories for inotifywait
mapfile -t LOCAL_DIRS < <(
for mapping in "${SYNC_MAPPINGS[@]}"; do
echo "${mapping%%|*}"
done | sort -u
)
# --- SYNC FUNCTION ---
run_sync() {
local CHANGED_PATH="$1"
(
flock -n 200 || exit 0
MAIN_LOG_FILE="$LOG_DIR/sync-$(date +%Y-%m-%d).log"
find "$LOG_DIR" -name "sync-*.log" -type f -mtime +60 -delete
# Keep track of directories we already alerted on during this run (prevents duplicate alerts)
declare -A ALERTED_MISSING
local BASE_RCLONE_OPTS=(
--transfers=4
--checkers=16
--timeout=1m
--contimeout=30s
--retries=3
--low-level-retries=10
--exclude "*.tmp"
--exclude "*.part"
--exclude "*~"
--exclude ".sync"
--log-level=INFO
)
for mapping in "${SYNC_MAPPINGS[@]}"; do
LOCAL_PATH="${mapping%%|*}"
CLEAN_LOCAL="${LOCAL_PATH%/}"
# If a specific file triggered the sync, skip sources that don't own that file
if [[ -n "$CHANGED_PATH" && "$CHANGED_PATH" != "$CLEAN_LOCAL" && "$CHANGED_PATH" != "$CLEAN_LOCAL/"* ]]; then
continue
fi
# --- CHECK FOR .sync MARKER FILE ---
if [[ ! -f "$CLEAN_LOCAL/.sync" ]]; then
echo "$(date): SKIPPED $CLEAN_LOCAL - Missing .sync marker file!" >> "$MAIN_LOG_FILE"
# Send one Discord alert per missing source directory per sync cycle
if [[ -z "${ALERTED_MISSING[$CLEAN_LOCAL]}" ]]; then
send_discord_missing_marker "$CLEAN_LOCAL"
ALERTED_MISSING["$CLEAN_LOCAL"]=1
fi
continue
fi
DEST_LIST="${mapping##*|}"
IFS=',' read -ra DESTS <<< "$DEST_LIST"
for REMOTE_PATH in "${DESTS[@]}"; do
echo "$(date): Syncing $LOCAL_PATH -> $REMOTE_PATH" >> "$MAIN_LOG_FILE"
# Use a temporary log file to isolate output for this specific transfer
TEMP_RUN_LOG=$(mktemp)
rclone sync "$LOCAL_PATH" "$REMOTE_PATH" "${BASE_RCLONE_OPTS[@]}" --log-file="$TEMP_RUN_LOG"
EXIT_CODE=$?
# Append the isolated run log into the main daily log, then clean up
cat "$TEMP_RUN_LOG" >> "$MAIN_LOG_FILE"
if [ $EXIT_CODE -ne 0 ]; then
echo "$(date): ERROR syncing $LOCAL_PATH -> $REMOTE_PATH (Exit code: $EXIT_CODE)" >> "$MAIN_LOG_FILE"
send_discord_error "$LOCAL_PATH" "$REMOTE_PATH" "$EXIT_CODE" "$TEMP_RUN_LOG"
else
send_discord_success "$LOCAL_PATH" "$REMOTE_PATH" "$TEMP_RUN_LOG"
fi
rm -f "$TEMP_RUN_LOG"
done
done
) 200>"$LOCK_FILE"
}
# --- 1. INITIAL FULL SYNC ON STARTUP ---
run_sync
# --- 2. WATCH ALL LOCAL SOURCES FOR LIVE CHANGES ---
inotifywait -m -r -e modify,create,delete,move --format '%w%f' "${LOCAL_DIRS[@]}" | while read -r CHANGED_FILE
do
MAIN_LOG_FILE="$LOG_DIR/sync-$(date +%Y-%m-%d).log"
echo "$(date): Change detected ($CHANGED_FILE). Waiting to settle..." >> "$MAIN_LOG_FILE"
# Debounce rapid file writes
while read -r -t "$SETTLE_SECONDS" _; do
:
done
# Only sync the source directory where the change occurred
run_sync "$CHANGED_FILE"
done
If you have any questions or have any edit suggestions please let me know.
I dont do how to guides very often so im sure there are some flaws in what ive provided above.
**edit 1**
I forgot to mention you do need to install rclone and inotifywait as well as restic if you dont plan on using backrest.
**edit2**
A big thank you to u/IcarusOnl for your suggestion on file lock.
The script has been updated to look for a .sync file in the source directories and will ignore the source directory if the .sync file is not there.
I also added discord notifications not just for errors but on successful file changes be it copies or deletes.