#! /bin/bash
# (c) by ennit interactive GmbH, 2015
# Author jbradler@ennit.com

# Include defaults if available
if [ -f /etc/default/hosting-tools ]; then
    . /etc/default/hosting-tools
fi

# MySQL root password can be stored in /root/mysql.pass (recommended for MySQL < 5.6
# later versions warn about commandline usage of passwords and you can use
# mysql_config_editor to store password encrypted:
# > mysql_config_editor set --login-path=client --host=localhost --user=root --password
if [ -f "/root/mysql.pass" ]; then
    . /root/mysql.pass
    CMD_PASSWORD="-p${MYSQL_PASS} "
else
    CMD_PASSWORD=""
fi

DB_EXISTS=0
USER_EXISTS=0

if [ "$#" -ne 3 ]; then
    echo "  [USAGE] $0 database username password"
    exit 1
fi

SIZE_USER=${#2}
if [ "$SIZE_USER" -gt 64 ]; then
    echo "  [ERROR] Max length of username is 64, given username is $SIZE_USER characters long."
    exit 1
fi

SIZE_PASS=${#3}
if [ "$SIZE_PASS" -lt 12 ]; then
    echo "  [ERROR] Min length of password is 12, given password is $SIZE_PASS characters long."
    exit 1
fi

if mysql -u "$MYSQL_USER" ${CMD_PASSWORD}--execute="SELECT EXISTS(SELECT schema_name FROM information_schema.schemata WHERE schema_name='$1') as result" | grep -o 1 > /dev/null ; then
    echo "  [WARNING] Database '$1' exists already, skipping creating database"
    DB_EXISTS=1
fi

if mysql -u "$MYSQL_USER" ${CMD_PASSWORD}--execute="SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$2') as result" | grep -o 1 > /dev/null ; then
    echo "  [WARNING] User '$2' exists already, skipping creating user"
    USER_EXISTS=1
fi

if [ $DB_EXISTS = 0 ]; then
mysql -u "$MYSQL_USER" ${CMD_PASSWORD}-t <<END
    CREATE DATABASE $1 CHARACTER SET utf8 COLLATE utf8_general_ci;
END
fi

if [ $USER_EXISTS = 0 ]; then
mysql -u "$MYSQL_USER" ${CMD_PASSWORD}-t <<END
    CREATE USER '$2'@'localhost' IDENTIFIED BY '$3';
END
fi

mysql -u "$MYSQL_USER" ${CMD_PASSWORD}-t <<END
    GRANT USAGE ON *.* TO '$2'@'localhost';
    GRANT ALL PRIVILEGES ON $1.* TO '$2'@'localhost';
    FLUSH PRIVILEGES;
    SHOW DATABASES LIKE '$1';
    SELECT user,host FROM mysql.user WHERE user = '$2';
END

exit 0