mb-backup-manager/scripts/imports/check_backup_repo.sh

66 lines
2.2 KiB
Bash
Raw Permalink Normal View History

#!/bin/bash
# Exit on errors
set -e
# Configuration
BACKUP_REPO_PATH="/mnt/backups"
PASSWORD_FILE="/etc/restic-password"
LOG_FILE="/var/log/backup_repo_check.log"
# Ensure the log file exists
mkdir -p "$(dirname "$LOG_FILE")"
# Logging function
log_message() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
# Main function to check the backup repository
check_backup_repo() {
# Ensure the backup repository path exists
mkdir -p "$BACKUP_REPO_PATH"
# Validate or create the password file
if [ ! -f "$PASSWORD_FILE" ]; then
log_message "Password file not found. Creating a new one with a default password."
echo "default-password" > "$PASSWORD_FILE"
fi
# Export the password and repository path for Restic
export RESTIC_PASSWORD=$(cat "$PASSWORD_FILE")
export RESTIC_REPOSITORY="$BACKUP_REPO_PATH"
# Check if the repository contains files
if [ "$(find "$BACKUP_REPO_PATH" -mindepth 1 | wc -l)" -gt 0 ]; then
log_message "Checking the backup repository integrity and consistency."
# Remove stale locks if they exist
if [ -d "$BACKUP_REPO_PATH/locks" ] && [ "$(ls -A "$BACKUP_REPO_PATH/locks")" ]; then
log_message "Stale lock detected in the repository. Removing lock."
if ! restic -r "$BACKUP_REPO_PATH" unlock; then
log_message "Failed to remove stale lock. Exiting."
exit 1
fi
fi
# Perform repository integrity check
if ! restic -q -r "$BACKUP_REPO_PATH" check --read-data-subset=5%; then
log_message "Repository integrity check failed. Please investigate."
exit 1
fi
log_message "Backup repository integrity check passed."
else
# Initialize a new Restic repository if empty
log_message "No files found in the backup repository. Initializing a new repository."
if ! restic init -r "$BACKUP_REPO_PATH"; then
log_message "Failed to initialize the backup repository. Exiting."
exit 1
fi
log_message "Backup repository initialized successfully."
fi
}
# Execute the function
check_backup_repo