|
cat ./run_db_functions.sh |
|
#!/bin/bash |
|
|
|
|
|
|
|
|
|
##### help================================>>>>>>>>>>>>>>>>>>>> |
|
|
|
# Function to display usage instructions |
|
display_help() { |
|
echo "Usage: $0 <database_name> [database_user] [database_password] " |
|
printf "\n" |
|
echo "Note : Database name is required , other fileds are optional" |
|
printf "\n" |
|
printf "If database_user and Database_password is not provided \nit will be created automaticaly from the database name " |
|
printf "\n" |
|
printf "\n" |
|
echo "Options:" |
|
echo " -h, --help Display this help message" |
|
} |
|
|
|
# Check for help option |
|
if [ "$1" == "-h" ] || [ "$1" == "--help" ] || [ "$1" == "" ]; then |
|
display_help |
|
exit 0 |
|
fi |
|
|
|
#### help==============================================>>>>>>>>>>>>>>>>> |
|
|
|
|
|
|
|
|
|
|
|
# MySQL credentials |
|
MYSQL_USER="root" |
|
MYSQL_PASSWORD="" |
|
|
|
# Get command-line arguments |
|
DB_NAME="$1" |
|
DB_USER="$2" |
|
DB_PASSWORD="$3" |
|
# Check if the database name is provided |
|
if [ -z "$DB_NAME" ]; then |
|
|
|
echo "Usage: $0 <database_name>" |
|
exit 1 |
|
fi |
|
|
|
|
|
if [ -z "$DB_USER" ]; then |
|
|
|
echo " Notice: User name is not provided , so creating a new user \n" |
|
DB_USER="${DB_NAME}_user" |
|
echo " Generated User ===> ${DB_USER}" |
|
fi |
|
|
|
|
|
# Generate password if not provided |
|
if [ -z "$DB_PASSWORD" ]; then |
|
|
|
echo " Notice: Database Password is not provided so creating a new passoword \n" |
|
DB_PASSWORD="${DB_NAME}_Password1#" |
|
echo " Generated Pass ===> ${DB_PASSWORD}" |
|
|
|
fi |
|
|
|
|
|
# MySQL command to create the database and user |
|
MYSQL_CMD="sudo mysql -u ${MYSQL_USER} " |
|
|
|
# Check if the user already exists |
|
USER_EXISTS=$(${MYSQL_CMD} -e "SELECT user FROM mysql.user WHERE user='${DB_USER}';" -s) |
|
|
|
if [ "${USER_EXISTS}" == "${DB_USER}" ]; then |
|
echo "User '${DB_USER}' already exists." |
|
|
|
# Create the user and grant privileges |
|
${MYSQL_CMD} -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';" |
|
${MYSQL_CMD} -e "FLUSH PRIVILEGES;" |
|
echo "User '${DB_USER}' only granted privileges as the user already exists." |
|
|
|
else |
|
# Create the database |
|
${MYSQL_CMD} -e "CREATE DATABASE ${DB_NAME};" |
|
echo "Database '${DB_NAME}' created." |
|
|
|
# Create the user and grant privileges |
|
${MYSQL_CMD} -e "CREATE USER '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASSWORD}';" |
|
${MYSQL_CMD} -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';" |
|
${MYSQL_CMD} -e "FLUSH PRIVILEGES;" |
|
echo "User '${DB_USER}' created and granted privileges." |
|
fi |