#!/bin/bash

# Set variables
MYSQL_BACKUP_DIR="/tmp/mysql_backup"
MYSQL_BACKUP_FILE="all_databases_backup.sql"

# Stop MySQL service
echo "Stopping MySQL service..."
sudo systemctl stop mysqld

# Backup all MySQL databases
echo "Backing up all databases..."
mkdir -p $MYSQL_BACKUP_DIR
sudo mysqldump -u root -p --all-databases > $MYSQL_BACKUP_DIR/$MYSQL_BACKUP_FILE

# Remove MySQL and related packages
echo "Removing MySQL and related packages..."
sudo yum remove -y mysql-server mysql mysql-libs

# Remove MySQL data and configuration files (This deletes your MySQL data, use with caution)
echo "Removing MySQL data and configuration files..."
sudo rm -rf /var/lib/mysql
sudo rm -f /etc/my.cnf
sudo rm -rf /etc/mysql
sudo rm -f /var/log/mysqld.log

# Install MySQL repository
echo "Installing MySQL repository..."
sudo wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm -O /tmp/mysql80-community-release-el7-3.noarch.rpm
sudo rpm -ivh /tmp/mysql80-community-release-el7-3.noarch.rpm

# Install MySQL server
echo "Installing MySQL server..."
sudo yum install -y mysql-server

# Start MySQL service
echo "Starting MySQL service..."
sudo systemctl start mysqld

# Enable MySQL to start on boot
echo "Enabling MySQL to start on boot..."
sudo systemctl enable mysqld

# Get the temporary MySQL root password
MYSQL_TEMP_PASSWORD=$(sudo grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')

# Secure MySQL installation
echo "Securing MySQL installation..."
sudo mysql_secure_installation <<EOF

$MYSQL_TEMP_PASSWORD
y
new_password_here
new_password_here
y
y
y
y
EOF

# Verify MySQL service status
echo "Verifying MySQL service status..."
sudo systemctl status mysqld

# Restore backup (optional, you may skip this if you want to start fresh)
echo "Restoring MySQL data..."
mysql -u root -p < $MYSQL_BACKUP_DIR/$MYSQL_BACKUP_FILE

echo "MySQL reinstallation complete!"