#!/bin/bash

# Function to log messages
log_message() {
    echo "$(date +"%Y-%m-%d %T") - $1" >> "$log_file"
}

# Function to remove backups older than 10 days
remove_old_backups() {
    if [ "$remove_old_backups_flag" = true ]; then
        find "$backup_base_dir" -mindepth 1 -type d -mtime +10 -exec rm -rf {} +
        if [ $? -eq 0 ]; then
            log_message "Old backups older than 10 days removed"
        else
            log_message "Error: Failed to remove old backups"
        fi
    else
        log_message "Skipping removal of old backups"
    fi
}

# Define backup directory base path
backup_base_dir="/home/backup_mysql"

# Create backup directory if it doesn't exist
if [ ! -d "$backup_base_dir" ]; then
    mkdir -p "$backup_base_dir"
fi

# Get current date
current_date=$(date +%Y-%m-%d)

# Create a directory for today's backup
backup_dir="$backup_base_dir/$current_date"
mkdir -p "$backup_dir"

# Define log file path
log_file="$backup_dir/mysql_backup_log.txt"

# Get list of MySQL databases
databases=$(mysql -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)")

# Start logging
log_message "Starting MySQL backup process"

# Loop through each database and backup
for db in $databases; do
    # Backup the database
    mysqldump $db > "$backup_dir/$db.sql"
    if [ $? -eq 0 ]; then
        log_message "Database '$db' backed up successfully"
    else
        log_message "Error: Failed to backup database '$db'"
    fi

    # Zip the database backup
    timestamp=$(date +%Y%m%d%H%M%S)
    zip -r "$backup_dir/$db-$timestamp.zip" "$backup_dir/$db.sql"
    if [ $? -eq 0 ]; then
        log_message "Database backup '$db-$timestamp.zip' zipped successfully"
    else
        log_message "Error: Failed to zip database backup '$db-$timestamp.zip'"
    fi

    # Remove the uncompressed database backup
    rm -f "$backup_dir/$db.sql"
    if [ $? -eq 0 ]; then
        log_message "Uncompressed backup file '$db.sql' removed"
    else
        log_message "Error: Failed to remove uncompressed backup file '$db.sql'"
    fi
done

# Remove backups older than 10 days
remove_old_backups_flag=${1:-true}
remove_old_backups

# End logging
log_message "MySQL backup process completed"

echo "MySQL databases backed up and zipped individually for $current_date."

