#!/bin/bash

# 颜色定义
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
RESET='\033[0m'

# 日志函数
log() {
    local level=$1
    local msg=$2
    case $level in
        INFO)    echo -e "${BLUE}[INFO]${RESET} $msg" ;;
        SUCCESS) echo -e "${GREEN}[SUCCESS]${RESET} $msg" ;;
        ERROR)   echo -e "${RED}[ERROR]${RESET} $msg" ;;
        WARNING) echo -e "${YELLOW}[WARNING]${RESET} $msg" ;;
    esac
}

# 检查并卸载旧版本
remove_old_versions() {
    log INFO "检查旧版本MySQL/MariaDB..."
    if rpm -qa | grep -E 'mysql|mariadb'; then
        log WARNING "发现旧版本，正在卸载..."
        yum remove -y mysql-* mariadb-* > /dev/null 2>&1
        rm -rf /var/lib/mysql /etc/my.cnf
    fi
}

# 安装MySQL
install_mysql() {
    log INFO "开始安装MySQL 8.0..."
    
    # 配置repo源（国内用户使用阿里云镜像）
    if ! curl -o /tmp/mysql80.rpm https://mirrors.aliyun.com/mysql/MySQL-8.0/mysql80-community-release-el7-7.noarch.rpm; then
        log ERROR "下载repo源失败，请检查网络"
        exit 1
    fi
    
    rpm -ivh /tmp/mysql80.rpm > /dev/null 2>&1
    rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2023

    # 安装服务
    if ! yum install -y mysql-community-server; then
        log WARNING "尝试禁用GPG检查安装..."
        yum install -y mysql-community-server --nogpgcheck || {
            log ERROR "MySQL安装失败"
            exit 1
        }
    fi
}

# 安全修改密码
secure_mysql() {
    log INFO "启动MySQL服务..."
    systemctl enable --now mysqld
    sleep 5  # 等待服务完全启动

    # 获取初始密码（多重验证）
    local temp_pass=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}' | tail -1)
    [ -z "$temp_pass" ] && {
        log ERROR "无法获取初始密码，请检查/var/log/mysqld.log"
        exit 1
    }

    log INFO "初始密码: $temp_pass"

    # 设置新密码（使用expect自动化交互）
    local new_pass="Chan1996!"  # 符合默认策略的密码
    
    if ! command -v expect > /dev/null; then
        yum install -y expect > /dev/null 2>&1
    fi

    log INFO "正在修改密码..."
    /usr/bin/expect <<EOF > /dev/null 2>&1
set timeout 20
spawn mysql -u root -p --connect-expired-password
expect "Enter password:"
send "$temp_pass\r"
expect "mysql>"
send "ALTER USER 'root'@'localhost' IDENTIFIED BY '$new_pass';\r"
expect "mysql>"
send "FLUSH PRIVILEGES;\r"
expect "mysql>"
send "exit\r"
expect eof
EOF

    # 验证新密码
    if mysql -u root -p"$new_pass" -e "SELECT 1;" &> /dev/null; then
        log SUCCESS "密码修改成功！新密码: $new_pass"
        
        # 写入环境变量（去重处理）
        sed -i '/export MYSQL_ROOT_PASS=/d' ~/.bashrc
        echo "export MYSQL_ROOT_PASS='$new_pass'" >> ~/.bashrc
        source ~/.bashrc
    else
        log ERROR "密码修改失败，请手动执行："
        echo "mysql -u root -p'$temp_pass' --connect-expired-password"
        echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '你的新密码';"
        exit 1
    fi
}

# 主执行流程
main() {
    remove_old_versions
    install_mysql
    secure_mysql
    
    echo -e "\n${GREEN}=== 安装完成 ===${RESET}"
    echo -e "MySQL root密码已保存到环境变量 ${YELLOW}MYSQL_ROOT_PASS${RESET}"
    echo -e "使用命令 ${BLUE}echo \$MYSQL_ROOT_PASS${RESET} 查看密码"
    echo -e "登录命令: ${GREEN}mysql -u root -p\$MYSQL_ROOT_PASS${RESET}"
}

# 执行主函数
main