#!/bin/sh
# create_db <database> [<user>]: creates a database (and its user) for the panel and prints the generated password.
# First makes sure root and the panel's smcore user can connect, recovering access when they can't (on CloudLinux
# by restarting the server without grant tables).

. /usr/local/sitemgr/lib/pkgsh/core_pkg_funcs.sh

[ -d /usr/local/sitemgr/etc ] || exit 1
mkdir -p /usr/local/sitemgr/tmp
[ -n "${1}" ] || exit 1

TMPCNF=/usr/local/sitemgr/tmp/.$$.cnf
CORECNF=/usr/local/sitemgr/etc/my.cnf
export PATH="${PATH}:/usr/sbin:/usr/bin:/bin:/sbin"

if DLIST=$(check_connect); then
	if ! check_my_cnf; then
		# root has no password
		create_root_passwd
		create_smcore_passwd
	fi
elif [ "$(OsName)" = cloudlinux ]; then
	skip_grant_mysql
	create_root_passwd
	systemctl restart ${MYSQL_SERVICE}
	create_smcore_passwd
fi

if ! DLIST=$(check_core_cnf); then
	if DLIST=$(check_connect); then
		create_smcore_passwd
	else
		OLDROOTPW=$(reset_root_passwd)
		create_smcore_passwd
		restore_root_passwd ${OLDROOTPW}
	fi
fi

PW=$(create_db ${1} ${2})
ret=$?
echo ${PW}
rm -f ${TMPCNF}
exit ${ret}
