#!/bin/bash

# Update the system
sudo apt update && sudo apt upgrade -y

# Install MySQL Server
sudo apt install mysql-server -y

# Configure MySQL root password and authentication
ROOT_PASS="fewr_-fd12"
sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$ROOT_PASS';"
sudo mysql -e "FLUSH PRIVILEGES;"

# Modify MySQL configuration to allow external connections
sudo sed -i "s/bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/" /etc/mysql/mysql.conf.d/mysqld.cnf

# Restart MySQL service
sudo systemctl restart mysql

# Create database and user
DB_NAME="defaultdb"
DB_USER="cemcoe"
DB_PASS="wodetian2025"

sudo mysql -u root -p"$ROOT_PASS" -e "CREATE DATABASE $DB_NAME;"
sudo mysql -u root -p"$ROOT_PASS" -e "CREATE USER '$DB_USER'@'%' IDENTIFIED BY '$DB_PASS';"
sudo mysql -u root -p"$ROOT_PASS" -e "GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'%';"
sudo mysql -u root -p"$ROOT_PASS" -e "FLUSH PRIVILEGES;"

# Configure the firewall
if ! sudo ufw status | grep -q "active"; then
  sudo ufw enable
fi
sudo ufw allow 3306/tcp

# Display statuses
sudo ufw status
sudo systemctl status mysql

echo "MySQL installation and configuration are complete!"
