#!/usr/bin/env bash

#
# Script to create MySQL/MariaDB db + user
#
# @author   Karel Wintersky <karel.wintersky@gmail.com>
# @version  0.4
# mysql_config_editor set --login-path=proftpd --host=localhost --user=proftpd --password
# version this: https://gist.github.com/KarelWintersky/72021fe214f9d2f6ddc6a28c732baac1
# version 0.2: https://gist.github.com/KarelWintersky/9cb12557873ebc59b5cb94cb37bb6913
#
#

_bold=$(tput bold)
_underline=$(tput sgr 0 1)
_reset=$(tput sgr0)

_purple=$(tput setaf 171)
_red=$(tput setaf 1)
_green=$(tput setaf 76)
_tan=$(tput setaf 3)
_blue=$(tput setaf 38)
_cyan=$(tput setaf 6)
_yellow=$(tput setaf 3)

function _success()
{
    printf "${_green}✔ %s${_reset}\n" "$@"
}

function _warning()
{
    printf "${_yellow}⚠ %s${_reset}\n" "$@"
}

function _error()
{
    printf "${_red}✖ %s${_reset}\n" "$@"
}

function _info()
{
    printf "${_blue}ℹ %s${_reset}\n" "$@"
}

function _debug()
{
    printf "${_cyan}🔧 %s${_reset}\n" "$@"
}

function _printPoweredBy()
{
    local db_type=$(detectDBType)
    local db_title="${_bold}${_blue}MySQL${_reset}"
    
    if [ "$db_type" = "mariadb" ]; then
        db_title="${_bold}${_purple}MariaDB${_reset}"
    fi
    
    echo ""
    echo "${_bold}################################################################${_reset}"
    echo "${_bold}${db_title} :: Create database, user and password${_reset}"
    echo "${_bold}(c) Karel Wintersky <karel.wintersky@gmail.com>, 2018${_reset}"
    echo "${_bold}################################################################${_reset}"
    echo ""
}

function detectDBType()
{
    local mysql_bin=$(which mysql 2>/dev/null)
    
    if [ -z "$mysql_bin" ]; then
        _error "MySQL client not found!"
        exit 1
    fi
    
    # Проверяем, является ли /usr/bin/mysql символической ссылкой
    if [ -L "/usr/bin/mysql" ]; then
        local link_target=$(readlink -f "/usr/bin/mysql")
        if [[ "$link_target" == *"mariadb"* ]]; then
            echo "mariadb"
            return
        fi
    fi
    
    # Дополнительная проверка через which mariadb
    local mariadb_bin=$(which mariadb 2>/dev/null)
    if [ -n "$mariadb_bin" ] && [ "$mysql_bin" = "$mariadb_bin" ]; then
        echo "mariadb"
        return
    fi
    
    echo "mysql"
}

function getDBBinary()
{
    local db_type=$(detectDBType)
    
    if [ "$db_type" = "mariadb" ]; then
        which mariadb
    else
        which mysql
    fi
}

function generatePassword()
{
    echo "$(openssl rand -base64 12)"
}

function getCredentials()
{
    _info "Please enter database credentials:"
    echo ""
    
    read -e -p "${_bold}${_blue}?${_reset} ${_bold}Enter the NAME of the new database:${_reset} " DBNAME
    read -e -p "${_bold}${_blue}?${_reset} ${_bold}Enter HOST for user access (% for remote access): ${_reset} " -i "localhost" USERHOST
    read -e -p "${_bold}${_blue}?${_reset} ${_bold}Enter the database CHARACTER SET (latin1, utf8): ${_reset} " -i "utf8mb4" CHARSET
    read -e -p "${_bold}${_blue}?${_reset} ${_bold}Enter the NAME of the user:${_reset} " -i "$DBNAME" USERNAME
    read -e -p "${_bold}${_blue}?${_reset} ${_bold}Enter the PASSWORD for the user:${_reset} " -i "$PASSWORD" PASSWORD
}

function getRootPassword()
{
    echo ""
    _warning "Root password required for database operations"
    read -e -p "${_bold}${_yellow}?${_reset} ${_bold}Enter MySQL/MariaDB root user password:${_reset} " -s ROOTPASSWORD
    echo ""

    ROOTACCESS="--user=root --password=${ROOTPASSWORD}"
}

function checkDBExist()
{
    local FOUND
    FOUND=$(${DB_BINARY} ${ROOTACCESS} -e "SHOW DATABASES LIKE '${DBNAME}';" | grep ${DBNAME})
    echo ${FOUND}
}

function checkUserExist()
{
    local FOUND
    FOUND=$(${DB_BINARY} ${ROOTACCESS} -e "SELECT COUNT(*) FROM mysql.user WHERE user = '${USERNAME}';" | grep 1)

    if [ "${FOUND}" = "1" ]; then
        echo "1"
    else
        echo "0"
    fi
}

function create()
{
    if [ ! -f ~/.my.cnf ]; then
        getRootPassword
    fi

    echo ""
    _info "Starting database creation process..."
    echo ""

    if [[ -n $(checkDBExist) ]]; then
        _warning "Database ${_bold}${DBNAME}${_reset} already exists!";
    else
        _info "Creating database ${_bold}${DBNAME}${_reset}..."
        ${DB_BINARY} ${ROOTACCESS} -e "CREATE DATABASE ${DBNAME} /*\!40100 DEFAULT CHARACTER SET ${CHARSET} */;"
        _success "Database ${_bold}${DBNAME}${_reset} successfully created!"
    fi

    echo ""

    if [ $(checkUserExist) = "0" ]; then
        _info "Creating new user ${_bold}${USERNAME}${_reset}..."
        ${DB_BINARY} ${ROOTACCESS} -e "CREATE USER ${USERNAME}@'${USERHOST}' IDENTIFIED BY '${PASSWORD}';"
        _success "User ${_bold}${USERNAME}${_reset} successfully created!"
    else
        _warning "User ${_bold}${USERNAME}${_reset} already exists!";
    fi

    echo ""

    _info "Granting ALL privileges on ${_bold}${DBNAME}${_reset} to ${_bold}${USERNAME}${_reset}..."
    ${DB_BINARY} ${ROOTACCESS} -e "GRANT ALL PRIVILEGES ON ${DBNAME}.* TO '${USERNAME}'@'${USERHOST}';"
    ${DB_BINARY} ${ROOTACCESS} -e "FLUSH PRIVILEGES;"
    _success "Privileges successfully granted!"
    echo ""
}

function printSuccessMessage()
{
    local db_type=$(detectDBType)
    local db_name="${_bold}${_blue}MySQL${_reset}"
    
    if [ "$db_type" = "mariadb" ]; then
        db_name="${_bold}${_purple}MariaDB${_reset}"
    fi
    
    _success "${db_name} database creation completed!"
    echo ""

    echo "${_bold}${_green}################################################################${_reset}"
    echo ""
    echo " ${_green}✓${_reset} ${_bold}Database Type:${_reset} ${db_name}"
    echo " ${_green}✓${_reset} ${_bold}Database:${_reset}      ${_green}${DBNAME}${_reset}"
    echo " ${_green}✓${_reset} ${_bold}User:${_reset}          ${_green}${USERNAME}${_reset}"
    echo " ${_green}✓${_reset} ${_bold}Password:${_reset}      ${_green}${PASSWORD}${_reset}"
    echo " ${_green}✓${_reset} ${_bold}Host:${_reset}          ${_green}${USERHOST}${_reset}"
    echo " ${_green}✓${_reset} ${_bold}Charset:${_reset}       ${_green}${CHARSET}${_reset}"
    echo ""
    echo "${_bold}${_green}################################################################${_reset}"
}

################################################################################
# Main
################################################################################
export LC_CTYPE=C
export LANG=C
VERSION="0.3"

# Определяем бинарник для работы с БД
DB_BINARY=$(getDBBinary)
DB_TYPE=$(detectDBType)

if [ -z "$DB_BINARY" ]; then
    _error "No database client found (mysql or mariadb)"
    exit 1
fi

ROOTACCESS=
ROOTPASSWORD=
CHARSET='utf8mb4';
DBNAME=
USERNAME=
USERHOST='localhost'
PASSWORD=$(generatePassword);

function main()
{
    _printPoweredBy

    getCredentials

    echo ""
    echo "${_bold}${_blue}################################################################${_reset}"
    echo ""

    create
    printSuccessMessage
}

main

exit 0