🌐 Overview

ThisBash script automates the backup and version control ofHomebridge andZigbee2MQTT configuration files usingGit, specificallyGitHub, for storage and version tracking. It begins by defining the locations for the log file, repository directory, and source directories for both Homebridge and Zigbee2MQTT. The script then navigates to the repository directory, identifies the latest backup files in the source directories, and copies them to designated directories within the repository. It logs each copy operation with a timestamp.

Following this, the script updates the local Git repository to reflect the latest state of the remote master branch, adds the newly copied backup files to the repository, and checks if there are any changes ready to be committed. If there are, it commits these changes with a timestamped message and pushes the commit to the remote master branch on GitHub. If the file addition fails, it logs an error message. This ensures that both Homebridge and Zigbee2MQTT configurations are backed up locally and securely stored remotely with an up-to-date version history.

Script Execution via CRON

This script has been designed to run automatically via aCRON job on the server, ensuring consistent and unattended backups and synchronization of Homebridge and Zigbee2MQTT configurations to GitHub.

🚀 Script

backup.sh
#!/bin/bash
 
log_file="/var/log/backup.log"
repo_dir="/var/www/backup/"
declare -A source_dirs=(
    ["homebridge"]="/var/www/homebridge/homebridge/backups/instance-backups/"
    ["zigbee2mqtt"]="/var/www/homebridge/zigbee2mqtt/backups/"
)
 
cd "$repo_dir"
 
for key in "${!source_dirs[@]}"; do
    source_dir=${source_dirs[$key]}
    backup_dir="${repo_dir}${key}/"
    latest_file=$(ls -t "$source_dir" | head -1)
    mkdir -p "$backup_dir"
    cp "${source_dir}${latest_file}" "$backup_dir"
    echo "$(date) - Copied $latest_file to $backup_dir" >> "$log_file"
    latest_files+=("${backup_dir}${latest_file}")
done
 
git fetch origin --prune
git checkout origin/master --force
 
git add "${latest_files[@]}"
if git status | grep -q "Changes to be committed"; then
    git commit -m "Backup Homebridge on $(date +'%Y-%m-%d %H:%M:%S')"
    git push origin HEAD:master
    echo "$(date) - Pushed backups to git" >> "$log_file"
else
    echo "$(date) - ERROR: Failed to add files to git" >> "$log_file"
fi