84 lines
1.8 KiB
Bash
Executable File
84 lines
1.8 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Exit on error.
|
|
set -e
|
|
|
|
# Command we pipe to execute the sql.
|
|
sql_cmd='mariadb -u root'
|
|
|
|
# SQL to create the database.
|
|
sql_create_db="CREATE DATABASE \`%s\`;"
|
|
|
|
# SQL to create user.
|
|
sql_create_user="CREATE USER IF NOT EXISTS '%s'@'%s' IDENTIFIED BY '%s';"
|
|
|
|
# SQL grant usage.
|
|
sql_grant_usage="GRANT USAGE ON *.* TO '%s'@'%s' IDENTIFIED BY '%s';"
|
|
|
|
# SQL grant on users database.
|
|
sql_grant_on_db="GRANT ALL privileges ON \`%s\`.* TO '%s'@'%s';"
|
|
|
|
# SQL flush
|
|
sql_flush='FLUSH PRIVILEGES;'
|
|
|
|
DB_HOST='localhost'
|
|
DB_USER=""
|
|
DB_NAME=""
|
|
DB_PASS=""
|
|
DB_PASS_REP=""
|
|
|
|
new_user() {
|
|
|
|
printf '(new) database user?\n' && read -t 120 DB_USER;
|
|
|
|
[[ ! "${DB_USER}" =~ ^[A-Za-z]{1}[A-Za-z0-9\_\-]+$ ]] && \
|
|
printf 'min 2 chars, A-z0-9_- allowed.. ' && new_user
|
|
|
|
return 0
|
|
}
|
|
|
|
new_db_name() {
|
|
|
|
printf '(new) database name?\n' && read -t 120 DB_NAME;
|
|
|
|
[[ ! "${DB_NAME}" =~ ^[A-Za-z]{1}[A-Za-z0-9\_\-]+$ ]] && \
|
|
printf 'min 2 chars, A-z0-9_- allowed.. ' && new_db_name
|
|
|
|
return 0
|
|
}
|
|
|
|
new_pass() {
|
|
|
|
printf 'password? (input hidden)\n' && read -st 120 DB_PASS;
|
|
printf 'password again?\n' && read -st 120 DB_PASS_REP;
|
|
|
|
[[ -z "$DB_PASS" ]] || [[ -z "$DB_PASS_REP" ]] && new_pass
|
|
[[ ! "$DB_PASS" == "$DB_PASS_REP" ]] && \
|
|
printf 'passwords do not match.. ' && new_pass
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
# Note: set -e requires the functions to return 0.
|
|
new_db_name
|
|
new_user
|
|
new_pass
|
|
|
|
# Create database.
|
|
printf "$sql_create_db" "$DB_NAME" | $sql_cmd;
|
|
|
|
# The user.
|
|
printf "$sql_create_user" "$DB_USER" "${DB_HOST:-NONE}" \
|
|
"$DB_PASS" | $sql_cmd;
|
|
|
|
# The grants.
|
|
printf "$sql_grant_usage" "$DB_USER" "${DB_HOST:-NONE}" \
|
|
"$DB_PASS" | $sql_cmd;
|
|
|
|
printf "$sql_grant_on_db" "$DB_NAME" "${DB_USER:-NONE}" \
|
|
"${DB_HOST:-NONE}" | $sql_cmd;
|
|
|
|
printf "$sql_flush" | $sql_cmd;
|
|
|