#!/bin/bash
# 2024-12

#获取脚本根目录，并设为只读
readonly INITDIR=$(cd $(dirname $0); dirname "$PWD")

if [ `rpm -qa | grep mariadb |wc -l` -ne 0 ];then
  echo -e "检测到mariadb存在"
  rpm -e --nodeps `rpm -qa | grep mariadb`
  echo -e "mariadb卸载完成"
else
  echo "未检测到mariadb存在"
fi

echo "卸载mysql"
yum -y remove mysql-community mysql-community-server mysql-community-client mysql-community-libs mysql-community-common
echo "清理mysql卸载残留"
\rm -rf /var/lib/mysql /usr/lib64/mysql /usr/share/mysql

yum -y install perl
yum -y install numactl
yum -y install libaio

echo exit | expect
Rs=$?
if [ $Rs -eq 0 ] ; then
  echo "expect,已经安装，继续！"
else 
  echo -e "\033[31mexpect异常！自动退出！\033[0m"
  exit 4
fi

perl -v  &> /dev/null
Rs=$?
if [ $Rs -eq 0 ] ; then 
  echo "perl,已经安装，继续！"
else
  echo -e "\033[31mperl异常！自动退出！\033[0m"
  exit 4
fi

echo "开始安装mysql"
rpm -ivh $INITDIR/file/mysql/mysql-community-common-5.7.42-1.el7.x86_64.rpm
rpm -ivh $INITDIR/file/mysql/mysql-community-libs-5.7.42-1.el7.x86_64.rpm
rpm -ivh $INITDIR/file/mysql/mysql-community-libs-compat-5.7.42-1.el7.x86_64.rpm
rpm -ivh $INITDIR/file/mysql/mysql-community-client-5.7.42-1.el7.x86_64.rpm
rpm -ivh $INITDIR/file/mysql/mysql-community-server-5.7.42-1.el7.x86_64.rpm
rpm -ivh $INITDIR/file/mysql/mysql-community-devel-5.7.42-1.el7.x86_64.rpm

mysqld --initialize --user=mysql
echo "配置mysql"
\cp $INITDIR/file/mysql/my.cnf.tmp /etc/my.cnf
echo "运行并进入mysql进行设置"
systemctl restart mysqld.service
systemctl enable mysqld.service
mysql --execute="update mysql.user set authentication_string=password('Zwkj@123Mysql') where user='root' and Host = 'localhost';"
mysql --execute="update mysql.user set authentication_string=password('Zwkj@123Mysql') where user='root' and Host = '%';"
echo "修改mysql配置文件"
\cp $INITDIR/file/mysql/my.cnf /etc/my.cnf

systemctl restart mysqld.service
echo "更新myslq密码"
$INITDIR/expect/mysql.expect
echo "初始化myslq数据库"
mysql --user="root" --password="Zwkj@123Mysql" --execute="GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY 'Zwkj@123Mysql' WITH GRANT OPTION;"
mysql --user="root" --password="Zwkj@123Mysql" --execute="FLUSH PRIVILEGES;"

#导入sql
$INITDIR/sh/mysql_init_sql.sh

echo "安装mysql完成"

