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

# 安装Nginx函数
install_nginx() {
    log "INFO" "开始安装Nginx..."
    
    # 检查是否已安装
    if command -v nginx &> /dev/null; then
        log "WARNING" "Nginx已安装，当前版本：$(nginx -v 2>&1)"
        return 0
    fi
    
    # 安装Nginx
    log "INFO" "安装Nginx及其依赖..."
    if yum install -y nginx; then
        log "SUCCESS" "Nginx安装成功"
    else
        log "ERROR" "Nginx安装失败"
        exit 1
    fi
}

# 启用并启动Nginx
enable_nginx() {
    log "INFO" "设置Nginx开机自启..."
    systemctl enable nginx
    
    log "INFO" "启动Nginx服务..."
    if systemctl start nginx; then
        log "SUCCESS" "Nginx服务启动成功"
    else
        log "ERROR" "Nginx服务启动失败"
        systemctl status nginx --no-pager
        exit 1
    fi
}

# 验证Nginx安装
verify_nginx() {
    log "INFO" "验证Nginx安装..."
    
    # 检查Nginx状态
    systemctl status nginx --no-pager
    
    # 检查Nginx版本
    nginx_version=$(nginx -v 2>&1)
    log "INFO" "Nginx版本: $nginx_version"
    
    # 检查Nginx配置是否有语法错误
    if nginx -t; then
        log "SUCCESS" "Nginx配置验证通过"
    else
        log "ERROR" "Nginx配置验证失败"
    fi
}

# 主函数
main() {
    log "INFO" "=== Nginx安装脚本开始执行 ==="
    
    # 检查是否有root权限
    if [ "$(id -u)" -ne 0 ]; then
        log "ERROR" "请使用root权限运行此脚本"
        exit 1
    fi
    
    # 安装Nginx
    install_nginx
    
    # 启用并启动Nginx
    enable_nginx
    
    # 验证安装
    verify_nginx
    
    log "SUCCESS" "=== Nginx安装完成 ==="
    log "INFO" "Nginx服务已启动并设置为开机自启"
    log "INFO" "配置文件位置: /etc/nginx/nginx.conf"
    log "INFO" "默认网站目录: /usr/share/nginx/html"
}

# 执行主函数
main