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

80 lines
2.6 KiB
Bash

#!/bin/bash
# Load backup logic functions
source /home/jelastic/mb-backups/backup-logic.sh
# Validate input parameters
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <RESTIC_PASSWORD> <ADDITIONAL_TAG>"
exit 1
fi
# Assign command line arguments to variables
RESTIC_PASSWORD="$1"
ADDITIONAL_TAG="$2"
# Configuration
APP_PATH='/var/www/webroot/ROOT'
WP_CONFIG="${APP_PATH}/wp-config.php"
backupPath='/mnt/backups'
password_file="/etc/restic-password"
LOG_DIR="/home/jelastic/mb-backups/logs"
LOG_FILE="${LOG_DIR}/backup_database_$(date +'%Y-%m-%d').log"
# Extract database credentials from wp-config.php
DB_NAME=$(grep "define( 'DB_NAME'" "$WP_CONFIG" | cut -d "'" -f 4)
DB_USER=$(grep "define( 'DB_USER'" "$WP_CONFIG" | cut -d "'" -f 4)
DB_PASSWORD=$(grep "define( 'DB_PASSWORD'" "$WP_CONFIG" | cut -d "'" -f 4)
# Backup user and password (optional)
BACKUP_USER='wp_backup'
BACKUP_PASSWORD='gaQjveXl24Xo66w'
# Ensure log directory exists
mkdir -p "$LOG_DIR"
# Set Restic and MySQL environment variables
export RESTIC_REPOSITORY="$backupPath"
export RESTIC_PASSWORD # Updated to use the command line argument
export MYSQL_PWD=$BACKUP_PASSWORD # Use the backup user's password for mysqldump
# Logging start
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Starting Database Backup with additional tag: $ADDITIONAL_TAG" | tee -a "$LOG_FILE"
# Verify that the password file exists and matches the supplied password
if [ ! -f "$password_file" ]; then
echo "ERROR: Password file not found at $password_file" | tee -a "$LOG_FILE"
exit 1
fi
# Load and verify password from the file
stored_password=$(cat "$password_file")
if [ "$stored_password" != "$RESTIC_PASSWORD" ]; then
echo "ERROR: Password mismatch. Aborting backup." | tee -a "$LOG_FILE"
exit 1
fi
# Verify backup path exists
if [ ! -d "$backupPath" ]; then
echo "ERROR: Backup path $backupPath does not exist." | tee -a "$LOG_FILE"
exit 1
fi
# Check repository accessibility and integrity
check_backup_repo
if [ $? -ne 0 ]; then
echo "[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: Backup repository check failed. Aborting backup." | tee -a "$LOG_FILE"
exit 1
fi
# Perform database backup with additional tag
if mysqldump -u "$BACKUP_USER" "$DB_NAME" | restic backup --stdin --stdin-filename "${DB_NAME}.sql" --tag wordpress_db --tag "$ADDITIONAL_TAG"; then
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Database backup completed successfully with tags: wordpress_db, $ADDITIONAL_TAG." | tee -a "$LOG_FILE"
else
echo "[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: Database backup failed." | tee -a "$LOG_FILE"
exit 1
fi
# Logging end
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Database Backup process finished." | tee -a "$LOG_FILE"