#!/bin/bash
# 数据库安装脚本 (install_mysql.sh)

echo "===== 开始安装MySQL数据库 ====="

# 配置项
MYSQL_TAR="mysql-5.7.16-1.el7.x86_64.rpm-bundle.tar"
INSTALL_DIR="/opt"
LOG_FILE="/var/log/mysql_install.log"
PASSWORD_FILE="/root/mysql_root_password.txt"
WORKDIR="/www/wwwroot/messages"
MYSQL_REPO_URL="https://dev.mysql.com/get/mysql80-community-release-el7-11.noarch.rpm"

# 生成安全密码
generate_secure_password() {
    local upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    local lower="abcdefghijklmnopqrstuvwxyz"
    local digit="0123456789"
    local symbol='!@#$%^&*()_+-=[]{};:,.<>?'

    local password=""
    password+="${upper:RANDOM%${#upper}:1}"
    password+="${lower:RANDOM%${#lower}:1}"
    password+="${digit:RANDOM%${#digit}:1}"
    password+="${symbol:RANDOM%${#symbol}:1}"

    local all="${upper}${lower}${digit}${symbol}"
    for (( i=4; i<16; i++ )); do
        password+="${all:RANDOM%${#all}:1}"
    done

    echo "$password" | fold -w1 | shuf | tr -d '\n'
    echo
}

# 日志记录
log_info() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 检查并安装 MySQL YUM 仓库
install_mysql_repo() {
    log_info "检查 MySQL YUM 仓库..."
    
    # 检查是否已存在 MySQL 仓库
    if [ -f /etc/yum.repos.d/mysql-community.repo ] || [ -f /etc/yum.repos.d/mysql-community-source.repo ]; then
        log_info "✅ MySQL YUM 仓库已存在"
        return 0
    fi
    
    log_info "安装 MySQL YUM 仓库..."
    yum -y install "$MYSQL_REPO_URL" || {
        log_info "❌ MySQL YUM 仓库安装失败，尝试备用下载方式..."
        
        # 尝试使用 wget 下载并安装
        wget -O /tmp/mysql-repo.rpm "$MYSQL_REPO_URL" || {
            log_info "❌ 无法下载 MySQL YUM 仓库包"
            return 1
        }
        
        yum -y localinstall /tmp/mysql-repo.rpm || {
            log_info "❌ MySQL YUM 仓库本地安装失败"
            rm -f /tmp/mysql-repo.rpm
            return 1
        }
        
        rm -f /tmp/mysql-repo.rpm
    }
    
    # 禁用 MySQL 8.0，启用 MySQL 5.7
    if command -v yum-config-manager &> /dev/null; then
        log_info "配置 MySQL 5.7 仓库..."
        yum-config-manager --disable mysql80-community >/dev/null 2>&1
        yum-config-manager --enable mysql57-community >/dev/null 2>&1
    else
        log_info "⚠️ yum-config-manager 不可用，手动配置仓库"
        sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/mysql-community.repo
        sed -i '/mysql57-community]/,/^\[/ s/enabled=0/enabled=1/' /etc/yum.repos.d/mysql-community.repo
    fi
    
    # 验证仓库配置
    if yum repolist enabled | grep -q mysql57-community; then
        log_info "✅ MySQL 5.7 仓库已启用"
        return 0
    else
        log_info "❌ MySQL 5.7 仓库启用失败"
        return 1
    fi
}

# 初始化日志
echo "===== MySQL安装开始 [$(date '+%Y-%m-%d %H:%M:%S')] =====" | tee "$LOG_FILE"

# 检查是否已安装
if rpm -qa | grep -q mysql-community-server; then
    log_info "⚠️ 检测到 MySQL 已安装，跳过安装步骤"

    if [ -f "$PASSWORD_FILE" ]; then
        log_info "🔐 MySQL root 密码文件已存在：$PASSWORD_FILE"
    else
        log_info "⚠️ 找不到 root 密码文件，请手动检查 /var/log/mysqld.log 或重置密码"
    fi

    cd "$WORKDIR" || {
        log_info "❌ 无法进入工作目录 $WORKDIR"
        exit 1
    }
    log_info "📂 已进入工作目录 $WORKDIR"
else
    # 安装流程

    # 检查内存大小（避免 yum 安装失败）
    MEM_TOTAL=$(grep MemTotal /proc/meminfo | awk '{print $2}')
    if (( MEM_TOTAL < 1024000 )); then
        log_info "⚠️ 内存小于 1GB，建议先添加 Swap 或升级服务器配置"
        read -p "是否继续安装？[y/N] " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_info "用户取消安装"
            exit 1
        fi
    fi

    # 安装 MySQL YUM 仓库
    if ! install_mysql_repo; then
        log_info "❌ MySQL YUM 仓库安装失败，继续使用 RPM 包安装方式"
    else
        log_info "✅ MySQL YUM 仓库安装成功"
        
        # 检查是否可以通过 yum 直接安装
        log_info "检查可用 MySQL 包..."
        if yum list available mysql-community-server 2>/dev/null | grep -q mysql-community-server; then
            log_info "✅ 检测到可通过 YUM 安装 MySQL，开始安装..."
            
            log_info "安装依赖库..."
            yum -y install ncurses-compat-libs libaio net-tools wget perl perl-Getopt-Long || {
                log_info "依赖安装失败!"
                exit 1
            }
            
            log_info "移除冲突包 mariadb..."
            yum remove -y mariadb-libs 2>/dev/null
            
            log_info "安装 MySQL..."
            yum -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-libs || {
                log_info "YUM 安装 MySQL 失败，回退到 RPM 包安装"
                # 继续执行下面的 RPM 安装流程
            } && {
                # YUM 安装成功，跳过 RPM 安装
                log_info "✅ MySQL 通过 YUM 安装成功"
                
                log_info "启动 MySQL 服务..."
                systemctl enable mysqld
                systemctl start mysqld || {
                    log_info "服务启动失败!"
                    exit 1
                }

                log_info "设置 root 密码..."
                TEMP_PASS=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')
                MYSQL_ROOT_PASS=$(generate_secure_password)

                mysql --connect-expired-password -uroot -p"$TEMP_PASS" -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASS';" 2>/dev/null
                if [ $? -ne 0 ]; then
                    log_info "密码修改失败，尝试使用安全模式修改..."
                    # 安全模式修改密码逻辑
                    systemctl stop mysqld
                    mysqld_safe --skip-grant-tables &
                    sleep 5
                    mysql -e "FLUSH PRIVILEGES; ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASS';"
                    pkill mysqld
                    sleep 3
                    systemctl start mysqld
                fi

                echo "$MYSQL_ROOT_PASS" > "$PASSWORD_FILE"
                chmod 600 "$PASSWORD_FILE"
                log_info "✅ MySQL root 密码已保存至 $PASSWORD_FILE"

                cd "$WORKDIR" || {
                    log_info "❌ 无法进入工作目录 $WORKDIR"
                    exit 1
                }

                log_info "📂 已进入工作目录 $WORKDIR"
                log_info "✅ MySQL 安装完成"
                echo "===== MySQL安装成功完成 =====" | tee -a "$LOG_FILE"
                echo "Root密码: $MYSQL_ROOT_PASS" | tee -a "$LOG_FILE"
                echo "连接命令: mysql -uroot -p'$MYSQL_ROOT_PASS'" | tee -a "$LOG_FILE"
                
                exit 0
            }
        fi
    fi

    # 继续原有的 RPM 包安装流程
    log_info "使用 RPM 包安装 MySQL..."

    # 检查 Perl 环境
    if ! command -v perl &> /dev/null; then
        log_info "正在安装 perl 及所需模块..."
        yum -y install perl perl-Getopt-Long perl-strict || {
            log_info "perl 安装失败，尝试安装 Perl 套件组..."
            yum -y groupinstall "Perl Support" || {
                log_info "无法安装 Perl 相关依赖，请检查网络或 YUM 源"
                exit 1
            }
        }
    fi

    # 验证 perl 模块是否可用
    perl -e 'use Getopt::Long; use strict;' 2>/dev/null || {
        log_info "× 缺少必要的 Perl 模块，请检查 Perl 安装"
        exit 1
    }

    log_info "安装依赖库..."
    yum -y install libaio net-tools wget || {
        log_info "依赖安装失败!"
        exit 1
    }

    cd "$INSTALL_DIR" || {
        log_info "无法进入安装目录 $INSTALL_DIR"
        exit 1
    }

    log_info "下载 MySQL 安装包..."
    wget -c "https://cdn.mysql.com/archives/mysql-5.7/$MYSQL_TAR" || {
        log_info "下载失败!"
        exit 1
    }

    log_info "解压安装包..."
    tar -xvf "$MYSQL_TAR" || {
        log_info "解压失败!"
        exit 1
    }

    log_info "移除冲突包 mariadb..."
    yum remove -y mariadb-libs 2>/dev/null

    log_info "导入 GPG 密钥..."
    rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql || {
        log_info "GPG 密钥导入失败!"
        exit 1
    }

    log_info "安装 MySQL 组件..."
    for pkg in common libs client server; do
        rpm -ivh "mysql-community-${pkg}-5.7.16-1.el7.x86_64.rpm" || {
            log_info "安装 mysql-community-${pkg} 失败!"
            exit 1
        }
    done

    log_info "启动 MySQL 服务..."
    systemctl enable mysqld
    systemctl start mysqld || {
        log_info "服务启动失败!"
        exit 1
    }

    log_info "设置 root 密码..."
    TEMP_PASS=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')
    MYSQL_ROOT_PASS=$(generate_secure_password)

    mysql --connect-expired-password -uroot -p"$TEMP_PASS" -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASS';"
    [ $? -ne 0 ] && {
        log_info "密码修改失败!"
        exit 1
    }

    mysql -uroot -p"$MYSQL_ROOT_PASS" <<EOF
UNINSTALL PLUGIN validate_password;
FLUSH PRIVILEGES;
EOF

    echo "$MYSQL_ROOT_PASS" > "$PASSWORD_FILE"
    chmod 600 "$PASSWORD_FILE"
    log_info "✅ MySQL root 密码已保存至 $PASSWORD_FILE"

    cd "$WORKDIR" || {
        log_info "❌ 无法进入工作目录 $WORKDIR"
        exit 1
    }

    log_info "📂 已进入工作目录 $WORKDIR"
    log_info "✅ MySQL 5.7 安装完成"
    echo "===== MySQL安装成功完成 =====" | tee -a "$LOG_FILE"
    echo "MySQL版本: 5.7.16" | tee -a "$LOG_FILE"
    echo "Root密码: $MYSQL_ROOT_PASS" | tee -a "$LOG_FILE"
    echo "连接命令: mysql -uroot -p'$MYSQL_ROOT_PASS'" | tee -a "$LOG_FILE"
    echo "安装日志: $LOG_FILE" | tee -a "$LOG_FILE"
    
    # 清理安装包
    rm -f "$INSTALL_DIR/mysql-community-"*.rpm
    rm -f "$INSTALL_DIR/$MYSQL_TAR"
    log_info "清理安装包完成"
fi

echo "===== MySQL数据库安装完成 ====="