#!/bin/bash # Exit on error and handle errors with a trap set -e trap 'log_message "ERROR: An error occurred during the backup process."' ERR # Function: Log messages log_message() { local message="$1" echo "[$(date +'%Y-%m-%d %H:%M:%S')] $message" | tee -a "$LOG_FILE" } # Check for required arguments if [ $# -ne 2 ]; then echo "Usage: $0 " exit 1 fi # Assign arguments to variables RESTIC_PASSWORD="$1" CUSTOM_LABEL="$2" # Configuration APP_PATH="/var/www/webroot/ROOT" BACKUP_PATH="/mnt/backups" PASSWORD_FILE="/etc/restic-password" LOG_DIR="/home/jelastic/mb-backups/logs" LOG_FILE="${LOG_DIR}/backup_core_files_$(date +'%Y-%m-%d').log" STATIC_TAG="core_files" # Static tag for this backup type EXCLUDE_PATHS=( "$APP_PATH/wp-content/uploads" ) LOCK_FILE="/tmp/restic_global.lock" # Ensure log directory exists mkdir -p "$LOG_DIR" # Validate password file and read password if [ ! -f "$PASSWORD_FILE" ]; then log_message "ERROR: Password file not found at $PASSWORD_FILE." exit 1 fi export RESTIC_PASSWORD=$(cat "$PASSWORD_FILE") # Verify repository access log_message "Verifying repository access..." if ! restic -r "$BACKUP_PATH" snapshots > /dev/null 2>&1; then log_message "ERROR: Unable to access the Restic repository. Aborting backup." exit 1 fi # Acquire a global lock to serialize Restic operations log_message "Acquiring global lock for Restic operations..." exec 9>"$LOCK_FILE" if ! flock -n 9; then log_message "Another Restic operation is running. Exiting." exit 1 fi log_message "Global lock acquired." # Check and remove stale locks log_message "Checking for stale locks in the repository..." if restic -r "$BACKUP_PATH" list locks | grep -q "lock"; then log_message "Stale locks detected. Unlocking the repository..." restic -r "$BACKUP_PATH" unlock log_message "Repository unlocked successfully." else log_message "No stale locks found." fi # Logging start log_message "Starting Core Files Backup with tags: $STATIC_TAG, $CUSTOM_LABEL" # Build exclude options EXCLUDE_OPTIONS="" for path in "${EXCLUDE_PATHS[@]}"; do EXCLUDE_OPTIONS+="--exclude $path " done # Perform backup if restic -r "$BACKUP_PATH" backup $EXCLUDE_OPTIONS "$APP_PATH" \ --tag "$STATIC_TAG" --tag "$CUSTOM_LABEL"; then log_message "Core files backup completed successfully." else log_message "ERROR: Core files backup failed." exit 1 fi # Release global lock exec 9>&- # Logging end log_message "Backup process finished successfully."