#!/usr/bin/env bash
set -o errexit

source ./common.sh

#install Mysql
MYSQL_TMP="/tmp/mysql"
MYSQL_PORT=3306
MYSQL_PASSWD=$(head /dev/urandom|base64|sed 's/[^A-Za-z0-9]//g'|cut -c1-10|head -n1)   #随机10位密码

##清除历史安装
rpm -qa|grep mysql
if [[ $?==0 ]];then
  rpm -qa |grep mysql |xargs rpm -e
  [ -f /etc/my.cnf ] && rm -f /etc/my.cnf
  [ -d /etc/my.cnf.d ] && rm -rf /etc/my.cnf.d
  [ -d /var/lib/mysql ] && rm -rf /var/lib/mysql 
fi

[ ! -e $MYSQL_TMP ] && mkdir -p $MYSQL_TMP
cd $MYSQL_TMP

cat >mysql_download_url <<EOF
http://soft.wujy.vip/mysql/mysql-community-client-5.7.28-1.el7.x86_64.rpm
http://soft.wujy.vip/mysql/mysql-community-common-5.7.28-1.el7.x86_64.rpm
http://soft.wujy.vip/mysql/mysql-community-devel-5.7.28-1.el7.x86_64.rpm
http://soft.wujy.vip/mysql/mysql-community-embedded-compat-5.7.28-1.el7.x86_64.rpm
http://soft.wujy.vip/mysql/mysql-community-libs-5.7.28-1.el7.x86_64.rpm
http://soft.wujy.vip/mysql/mysql-community-libs-compat-5.7.28-1.el7.x86_64.rpm
http://soft.wujy.vip/mysql/mysql-community-server-5.7.28-1.el7.x86_64.rpm
EOF

wget -i mysql_download_url
rpm -ivh mysql-community* --nodeps --force
echo -e "\ncharacter_set_server=utf8mb4" >> /etc/my.cnf

systemctl start mysqld
systemctl enable mysqld

tmp_password=$(grep "temporary password" /var/log/mysqld.log|awk '{print $11}')

#systemctl enable firewalld
#systemctl start firewalld
#firewall-cmd --add-port=${MYSQL_PORT}/tcp --permanent
#firewall-cmd --add-port=22/tcp --permanent
#firewall-cmd --reload
#
#rm -rf $MYSQL_TMP

mysql -uroot -p${tmp_password} <<EOF
alter user user() identified by "${MYSQL_PASSWD}";
grant all privileges on *.* to root@'%' identified by "${MYSQL_PASSWD}";
EOF

echo -e "Mysql数据库已经安装成功。"
echo -e "数据库初始密码是：\033[0;31m${MYSQL_PASSWD}\033[0m"
