#!/bin/sh
# mysql_passwd: prints the database root password from /root/.my.cnf, giving root a password first when it has none
# and resetting it when root can't connect (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

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
	check_my_cnf || create_root_passwd
elif ! check_my_cnf && [ "$(OsName)" = cloudlinux ]; then
	skip_grant_mysql
	create_root_passwd
	systemctl restart ${MYSQL_SERVICE}
else
	reset_root_passwd
	cp -f ${TMPCNF} /root/.my.cnf
	chmod 600 /root/.my.cnf
fi

ROOTPW=$(awk -F= '$1 ~ "^password" {print $2}' /root/.my.cnf | sed 's/ //g')
echo ${ROOTPW}
