#!/bin/bash
# MySQL配置验证脚本
# 用于验证MySQL配置文件与MySQL 8.0的兼容性

set -e

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

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查MySQL 8.0不兼容的配置项
check_mysql8_compatibility() {
    local config_file="$1"
    local issues_found=0
    
    log_info "检查配置文件: $config_file"
    
    if [[ ! -f "$config_file" ]]; then
        log_error "配置文件不存在: $config_file"
        return 1
    fi
    
    # 检查已移除的sql_mode选项
    if grep -q "NO_AUTO_CREATE_USER" "$config_file"; then
        log_error "发现不兼容的sql_mode选项: NO_AUTO_CREATE_USER (MySQL 8.0已移除)"
        ((issues_found++))
    fi
    
    # 检查已弃用的参数
    if grep -q "expire_logs_days" "$config_file"; then
        log_warn "发现已弃用的参数: expire_logs_days (建议使用 binlog_expire_logs_seconds)"
        ((issues_found++))
    fi
    
    if grep -q "binlog_format.*STATEMENT" "$config_file"; then
        log_warn "发现已弃用的binlog_format: STATEMENT (建议使用 ROW)"
    fi
    
    # 检查query_cache相关配置 (MySQL 8.0已移除)
    if grep -v "^[[:space:]]*#" "$config_file" | grep -q "query_cache"; then
        log_warn "发现query_cache相关配置 (MySQL 8.0已移除查询缓存功能)"
    fi
    
    # 检查推荐的安全配置
    if ! grep -q "sql_mode.*STRICT_TRANS_TABLES" "$config_file"; then
        log_warn "建议在sql_mode中包含 STRICT_TRANS_TABLES"
    fi
    
    return $issues_found
}

# 主函数
main() {
    log_info "MySQL 8.0配置兼容性检查"
    echo "========================================"
    
    local total_issues=0
    local config_files=(
        "../configs/my.cnf.dev"
        "../configs/my.cnf.staging" 
        "../configs/my.cnf.prod"
    )
    
    for config_file in "${config_files[@]}"; do
        if check_mysql8_compatibility "$config_file"; then
            log_success "配置文件检查通过: $(basename "$config_file")"
        else
            local issues=$?
            total_issues=$((total_issues + issues))
            log_error "配置文件存在 $issues 个问题: $(basename "$config_file")"
        fi
        echo ""
    done
    
    echo "========================================"
    if [[ $total_issues -eq 0 ]]; then
        log_success "所有配置文件检查通过!"
    else
        log_error "总共发现 $total_issues 个配置问题"
        echo ""
        log_info "修复建议:"
        echo "1. 移除 NO_AUTO_CREATE_USER 从 sql_mode"
        echo "2. 将 expire_logs_days 替换为 binlog_expire_logs_seconds"
        echo "3. 移除或注释 query_cache 相关配置"
        echo "4. 确保 sql_mode 包含推荐的安全选项"
    fi
    
    return $total_issues
}

# 如果脚本被直接执行
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    cd "$(dirname "${BASH_SOURCE[0]}")"
    main "$@"
fi