#!/bin/zsh
# Script Version: 1.1
# Description: Create MySQL Database and User (same name) with generated password
# Set variables
DBNAME=$1
PASSWORD=""
LOG_FILE="/var/log/mysql_db_user_creation.log"
# Functions
ask_for_input() {
if [ -z "$DBNAME" ]; then
read "DBNAME?Enter the database and username: "
fi
}
generate_password() {
PASSWORD=$(openssl rand -base64 12)
}
create_db_and_user() {
echo "Creating MySQL Database and User..."
mysql -u root -p <<EOF
CREATE DATABASE IF NOT EXISTS \`$DBNAME\`;
CREATE USER IF NOT EXISTS '$DBNAME'@'localhost' IDENTIFIED BY '$PASSWORD';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES ON \`$DBNAME\`.* TO '$DBNAME'@'localhost';
FLUSH PRIVILEGES;
EOF
if [ $? -eq 0 ]; then
echo "Database and user '$DBNAME' created successfully."
echo "Generated password for user '$DBNAME': $PASSWORD"
echo "Database and user '$DBNAME' created successfully. Password: $PASSWORD" >> $LOG_FILE
else
echo "Error creating database or user. Check MySQL configuration and permissions."
fi
}
# Main Process
ask_for_input
generate_password
create_db_and_user