vhost-stack/bin/vhost-mysql-db-add.sh
2021-09-16 16:21:35 -07:00

92 lines
2.7 KiB
Bash
Executable File

#!/bin/bash
#
# vhost-stack
# https://git.stack-source.com/msb/vhost-stack
# MIT License Copyright (c) 2021 Matthew Saunders Brown
# load include file
source $(dirname $0)/vhost.sh
help()
{
thisfilename=$(basename -- "$0")
echo "Creates default MySQL database and db user for specified virtualhost."
echo ""
echo "usage: $thisfilename virtualhost. [OPTIONS]"
echo ""
echo " -h Print this help."
echo " -u USERNAME Username for accessing the database. Optional, autogenerated if none specified."
echo " -p PASSWORD Password for username. Optional, random password generated if none specified."
echo ""
echo " MySQL database names is based on virtualhost, with . replaced by the word 'dot'"
echo " and - replaced by the word 'dash'. If username is autogenerated it is based on"
echo " the shell username & the virtualhost name."
echo " e.g. for virtualost example.com the db name will be 'exampledotcom' and the"
echo " username will be examplec@example.com."
echo " db info stored in a file named /srv/www/$virtualhost/db_info.txt"
exit
}
# check for and set virtualhost
if [ -n "$1" ]; then
if [ $1 == "-h" ]; then
help
else
virtualhost="${1,,}"
shift
fi
else
echo "virtualhost not set"
exit 1
fi
# make sure virtualhost exists
if [ ! -d /srv/www/$virtualhost ]; then
echo "virtualhost $virtualhost does not exist"
exit 1
fi
# set database name
database=${virtualhost//./dot}
database=${database//-/dash}
# make sure database doesn't already exist
if [ -d /var/lib/mysql/$database ]; then
echo "database $database already exists"
exit 1
fi
# get & set username of virtualhost
vhost_username=$(stat -c '%U' /srv/www/$virtualhost)
# check for and set mysql username
if [ -n "$2" ]; then
username=$2
else
username=$vhost_username@$virtualhost
fi
# check for and set mysql password
if [ -n "$3" ]; then
password=$3
else
password=`/usr/bin/pwgen 16 1`
fi
mysqladmin create $database
mysql -e "CREATE USER '$username'@'localhost' IDENTIFIED BY '$password';"
mysql -e "GRANT ALL PRIVILEGES ON $database.* TO '$username'@'localhost';"
mysqladmin flush-privileges
# save mysql db info to file
touch /srv/www/$virtualhost/db_info.txt
chown $vhost_username:$vhost_username /srv/www/$virtualhost/db_info.txt
chmod 640 /srv/www/$virtualhost/db_info.txt
echo "hostname=127.0.0.1" > /srv/www/$virtualhost/db_info.txt
echo "database=$database" >> /srv/www/$virtualhost/db_info.txt
echo "username=$username" >> /srv/www/$virtualhost/db_info.txt
echo "password=$password" >> /srv/www/$virtualhost/db_info.txt
echo "database '$database' created with username '$username' and password '$password'"