#!/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
}

# 检查并安装必备工具
install_prerequisites() {
    log INFO "检查并安装必备工具..."
    local required_tools=("wget" "curl" "rpm" "yum" "expect" "sudo" "grep" "awk" "sed" "systemctl")
    
    for tool in "${required_tools[@]}"; do
        if ! command -v "$tool" &> /dev/null; then
            log WARNING "$tool 未安装，正在安装..."
            if sudo yum install -y "$tool"; then
                log INFO "$tool 安装成功"
            else
                log ERROR "$tool 安装失败，脚本终止"
                exit 1
            fi
        else
            log INFO "$tool 已安装"
        fi
    done
}

# 检查并卸载旧版本
remove_old_versions() {
    log INFO "检查旧版本 MySQL/MariaDB..."
    local old_packages=$(rpm -qa | grep -E 'mysql|mariadb')
    if [ -n "$old_packages" ]; then
        log WARNING "发现旧版本，正在卸载..."
        if sudo yum remove -y mysql-* mariadb-* > /dev/null 2>&1; then
            log INFO "旧版本已卸载"
            sudo rm -rf /var/lib/mysql /etc/my.cnf
            log INFO "残留文件已清除"
        else
            log ERROR "旧版本卸载失败，请手动处理"
            exit 1
        fi
    else
        log INFO "未发现旧版本"
    fi
}

# 安装MySQL仓库配置
install_repo() {
    local repo_urls=(
        "https://mirrors.aliyun.com/mysql/MySQL-8.0/mysql80-community-release-el7-7.noarch.rpm"  # 阿里云镜像优先
        "https://dev.mysql.com/get/mysql80-community-release-el7-7.noarch.rpm"  # 官方源
        "https://repo.mysql.com//mysql80-community-release-el7-7.noarch.rpm"   # 备用官方源
    )
    local repo_rpm="mysql80-community-release-el7-7.noarch.rpm"

    # 下载仓库配置
    for url in "${repo_urls[@]}"; do
        log INFO "尝试从 $url 下载仓库配置..."
        if curl -sS --retry 3 -o "$repo_rpm" "$url"; then
            if [ -s "$repo_rpm" ]; then
                log SUCCESS "仓库配置下载成功"
                break
            else
                log WARNING "下载的文件为空，尝试下一个链接..."
                rm -f "$repo_rpm"
            fi
        else
            log WARNING "下载失败，尝试下一个链接..."
        fi
    done

    if [ ! -s "$repo_rpm" ]; then
        log ERROR "所有镜像源下载失败，请检查网络连接"
        exit 1
    fi

    # 安装仓库
    log INFO "安装仓库配置..."
    if ! sudo rpm -Uvh "$repo_rpm"; then
        log ERROR "仓库配置安装失败"
        exit 1
    fi

    # 更新缓存并配置仓库
    log INFO "更新YUM缓存..."
    sudo yum clean all > /dev/null 2>&1
    sudo yum makecache > /dev/null 2>&1

    # 启用MySQL 8.0仓库并禁用其他版本
    log INFO "配置仓库优先级..."
    sudo sed -i -e 's/enabled=1/enabled=0/g' /etc/yum.repos.d/mysql-community*.repo
    sudo sed -i -e '/\[mysql80-community\]/,/^\[/ s/enabled=0/enabled=1/' /etc/yum.repos.d/mysql-community.repo
    
    log SUCCESS "仓库配置完成"
}

# 安装MySQL服务
install_mysql_server() {
    # 安装系统依赖
    log INFO "安装系统依赖..."
    sudo yum install -y openssl-devel libaio perl ncurses-compat-libs > /dev/null 2>&1

    # 检查仓库有效性
    log INFO "验证仓库包..."
    if ! yum --disablerepo=* --enablerepo=mysql80-community list available mysql-community-server &> /dev/null; then
        log ERROR "仓库中未找到MySQL 8.0软件包"
        exit 1
    fi

    # 安装MySQL组件
    log INFO "开始安装MySQL..."
    if ! sudo yum install -y mysql-community-server mysql-community-client mysql-community-common mysql-community-icu-data-files; then
        log WARNING "常规安装失败，尝试跳过GPG检查..."
        if ! sudo yum install -y mysql-community-server mysql-community-client mysql-community-common --nogpgcheck; then
            log ERROR "MySQL安装失败"
            exit 1
        fi
    fi
    log SUCCESS "MySQL安装完成"
}

# 初始化服务
secure_mysql() {
    log INFO "启动MySQL服务..."
    sudo systemctl enable --now mysqld > /dev/null 2>&1

    # 等待服务启动
    local timeout=30
    while [ $timeout -gt 0 ]; do
        if systemctl is-active mysqld > /dev/null; then
            break
        fi
        sleep 1
        ((timeout--))
    done
    [ $timeout -eq 0 ] && log WARNING "服务启动超时"

    # 获取初始密码
    log INFO "获取初始密码..."
    local temp_pass=$(sudo grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}' | tail -1)
    if [ -z "$temp_pass" ]; then
        log ERROR "无法获取初始密码，请检查日志：/var/log/mysqld.log"
        exit 1
    fi

    # 设置新密码
    local new_pass="Chan1996!"
    log INFO "修改root密码..."
    
    /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 2>&1; then
        log SUCCESS "密码修改成功！新密码：$new_pass"
        # 保存环境变量
        echo "export MYSQL_ROOT_PASS='$new_pass'" | sudo tee -a /etc/profile > /dev/null
        source /etc/profile
    else
        log ERROR "密码修改失败，请手动执行："
        echo "mysql -u root -p'$temp_pass' --connect-expired-password"
        echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '你的新密码';"
        exit 1
    fi
}

# 清理临时文件
cleanup() {
    log INFO "清理临时文件..."
    sudo rm -f mysql80-community-release-el7-7.noarch.rpm > /dev/null 2>&1
    log SUCCESS "安装完成"
}

# 主函数
main() {
    echo -e "\n${GREEN}=== MySQL 8.0 自动安装脚本 ===${RESET}"
    install_prerequisites
    remove_old_versions
    install_repo
    install_mysql_server
    secure_mysql
    cleanup

    echo -e "\n${GREEN}=== 安装结果 ===${RESET}"
    echo -e "• 服务状态: ${BLUE}$(systemctl is-active mysqld)${RESET}"
    echo -e "• 默认密码: ${YELLOW}$new_pass${RESET}"
    echo -e "• 登录命令: ${GREEN}mysql -u root -p\$MYSQL_ROOT_PASS${RESET}"
    echo -e "• 配置文件: ${BLUE}/etc/my.cnf${RESET}"
}

# 执行主函数
main