#encoding: utf-8
#!/bin/bash

user=`whoami`
localPwd="$( cd "$( dirname "$0"   )" && pwd   )"

sudoCmd=""
[ "$user" != "root" ] && sudoCmd="sudo " && echo "非root用户，使用免密sudo命令执行。"

function echo_info {
echo -e "\e[32m`printf '%-20s' "[install_nginx]"`\e[0m - $1"
}
function echo_warn {
echo -e "\e[31m`printf '%-20s' "[install_nginx]"`\e[0m - $1"
}

function main() {
 [ -f ${localPwd}/mysql-5.7.44.tgz ] && mysqlInstallFile="${localPwd}/mysql-5.7.44.tgz"
 [ -z "$mysqlInstallFile" ] && [ -f ${localPwd}/../mysql-5.7.44.tgz ] && mysqlInstallFile="${localPwd}/../mysql-5.7.44.tgz"
 [ -z "$mysqlInstallFile" ] && echo "ERROR - no tgz" && exit 1
 [ ! -f ${localPwd}/conf/my.cnf ] && echo "ERROR - no my.cnf" && exit 1
 [ -e /data/mysql ] && read -p  "数据目录[/data/mysql]存在.是否停止安装?[y/n]" continueTag
 [ -n "$continueTag" ] && [ "$continueTag" = "y" ] && exit 0
 tar xzf ${mysqlInstallFile} -C ${localPwd}
 $sudoCmd yum localinstall ${localPwd}/mysql-5.7.44/* -y
 $sudoCmd \cp ${localPwd}/conf/my.cnf /etc/my.cnf
 $sudoCmd systemctl enable mysqld 
 $sudoCmd systemctl start mysqld
 if [ $? -eq 0 ];then
  mysqlpd=`$sudoCmd cat /var/log/mysqld.log |grep "A temporary password" |tail -n 1|awk -F ": " '{print $NF}'`
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'R00t@1298';flush privileges" 2>/dev/null
  mysqlpd="R00t@1298"
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "GRANT all privileges ON *.* TO 'app'@'%' identified by 'Shuq1@1298';flush privileges;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "GRANT all privileges ON *.* TO 'app'@'127.0.0.1' identified by 'Shuq1@1298';flush privileges;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "GRANT all privileges ON *.* TO 'app'@'localhost' identified by 'Shuq1@1298';flush privileges;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "GRANT all privileges ON starry.* TO 'starry'@'%' identified by 'Shuq1-1298';flush privileges;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "GRANT all privileges ON starry.* TO 'starry'@'127.0.0.1' identified by 'Shuq1-1298';flush privileges;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "GRANT all privileges ON starry.* TO 'starry'@'localhost' identified by 'Shuq1-1298';flush privileges;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "create database hive DEFAULT CHARACTER SET utf8;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "create database starry DEFAULT CHARACTER SET utf8;" 2>/dev/null
  mysql -uroot -p${mysqlpd} --connect-expired-password -e "create database ranger DEFAULT CHARACTER SET utf8;" 2>/dev/null
 fi
}

main
