#!/bin/bash

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

# 日志函数
log() {
    local level=$1
    local message=$2
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    case $level in
        "INFO")
            echo -e "${BLUE}[INFO] $timestamp - $message${NC}"
            ;;
        "ERROR")
            echo -e "${RED}[ERROR] $timestamp - $message${NC}"
            ;;
        "WARNING")
            echo -e "${YELLOW}[WARNING] $timestamp - $message${NC}"
            ;;
        "SUCCESS")
            echo -e "${GREEN}[SUCCESS] $timestamp - $message${NC}"
            ;;
        *)
            echo -e "[UNKNOWN] $timestamp - $message"
            ;;
    esac
}

# 检查是否有root权限
if [ "$(id -u)" -ne 0 ]; then
    log "ERROR" "请使用root权限运行此脚本"
    exit 1
fi

# 运行前置检查脚本
log "INFO" "执行系统前置检查..."
if [ -f "pre_check.sh" ]; then
    chmod +x pre_check.sh
    ./pre_check.sh
    if [ $? -ne 0 ]; then
        log "ERROR" "系统前置检查未通过，安装终止"
        exit 1
    fi
    log "SUCCESS" "系统前置检查通过，继续安装"
else
    log "WARNING" "未找到前置检查脚本(pre_check.sh)，跳过系统检查"
fi

# 检查脚本执行权限
check_script() {
    local script=$1
    if [ ! -f "$script" ]; then
        log "ERROR" "脚本 $script 不存在"
        return 1
    fi
    
    chmod +x "$script"
    return 0
}

# 运行安装脚本
run_install_script() {
    local script=$1
    local name=$2
    
    log "INFO" "===== 开始安装 $name ====="
    
    if check_script "$script"; then
        log "INFO" "执行脚本: $script"
        if ./"$script"; then
            log "SUCCESS" "$name 安装完成"
        else
            log "ERROR" "$name 安装失败，错误代码: $?"
            exit 1
        fi
    else
        log "ERROR" "无法执行 $name 安装脚本"
        exit 1
    fi
    
    log "INFO" "===== $name 安装完成 ====="
    echo ""
}

# 主函数
main() {
    log "INFO" "============================================"
    log "INFO" "      服务器环境一键安装脚本开始执行"
    log "INFO" "============================================"
    
    # 1. 安装Python 3.9
    run_install_script "install_python.sh" "Python 3.9"
    
    # 2. 安装MySQL 8
    run_install_script "install_mysql8_6th.sh" "MySQL 8"
    
    # 3. 安装Redis
    run_install_script "install_redis.sh" "Redis"
    
    # 4. 安装Nginx
    run_install_script "install_nginx.sh" "Nginx"
    
    log "SUCCESS" "============================================"
    log "SUCCESS" "      所有组件安装完成！"
    log "SUCCESS" "============================================"
    log "INFO" "已安装组件:"
    log "INFO" "- Python: $(python3 --version 2>&1)"
    log "INFO" "- MySQL: $(mysql --version 2>&1 || echo '获取版本失败，可能需要手动检查')"
    log "INFO" "- Redis: $(redis-cli --version 2>&1 || echo '获取版本失败，可能需要手动检查')"
    log "INFO" "- Nginx: $(nginx -v 2>&1 || echo '获取版本失败，可能需要手动检查')"
    
    # 环境变量提醒
    log "INFO" "请运行以下命令使环境变量生效:"
    echo "source /etc/profile && source ~/.bashrc"
}

# 执行主函数
main