#!/bin/bash
# 环境变量检查脚本
# 用于验证容器中的环境变量是否正确加载

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"
}

# 检查环境文件
check_env_file() {
    log_info "检查环境配置文件..."
    
    if [[ -f "environments/.env.production" ]]; then
        log_success "✓ 找到生产环境配置文件"
        
        echo "环境文件内容:"
        echo "----------------------------------------"
        cat environments/.env.production | grep -E "^(DB_|REDIS_|BACKEND_|SPRING_)" | while read line; do
            if [[ $line == *"PASSWORD"* ]]; then
                echo "  ${line%%=*}=[HIDDEN]"
            else
                echo "  $line"
            fi
        done
        echo "----------------------------------------"
    else
        log_error "✗ 未找到生产环境配置文件"
        return 1
    fi
}

# 检查docker-compose配置
check_compose_config() {
    log_info "检查docker-compose环境变量配置..."
    
    if [[ -f "docker-compose.production.yml" ]]; then
        log_success "✓ 找到docker-compose配置文件"
        
        # 显示后端服务的环境变量配置
        echo "后端服务环境变量配置:"
        echo "----------------------------------------"
        sed -n '/anxin-backend:/,/ports:/p' docker-compose.production.yml | grep -E "^\s+[A-Z_]+:" | head -20
        echo "----------------------------------------"
    else
        log_error "✗ 未找到docker-compose配置文件"
        return 1
    fi
}

# 检查容器环境变量
check_container_env() {
    log_info "检查容器内环境变量..."
    
    if docker ps --filter "name=anxin-backend-prod" --format "{{.Names}}" | grep -q "anxin-backend-prod"; then
        log_success "✓ 后端容器正在运行"
        
        echo "容器内环境变量:"
        echo "----------------------------------------"
        echo "数据库配置:"
        docker exec anxin-backend-prod env | grep -E "^DB_" | while read line; do
            if [[ $line == *"PASSWORD"* ]]; then
                echo "  ${line%%=*}=[HIDDEN]"
            else
                echo "  $line"
            fi
        done
        
        echo ""
        echo "Redis配置:"
        docker exec anxin-backend-prod env | grep -E "^REDIS_" | while read line; do
            if [[ $line == *"PASSWORD"* ]]; then
                echo "  ${line%%=*}=[HIDDEN]"
            else
                echo "  $line"
            fi
        done
        
        echo ""
        echo "Spring配置:"
        docker exec anxin-backend-prod env | grep -E "^SPRING_" | head -5
        
        echo ""
        echo "其他配置:"
        docker exec anxin-backend-prod env | grep -E "^(LOG_LEVEL|SERVER_PORT|JAVA_OPTS)" | head -5
        echo "----------------------------------------"
    else
        log_error "✗ 后端容器未运行"
        return 1
    fi
}

# 对比配置差异
compare_configs() {
    log_info "对比配置差异..."
    
    if [[ -f "environments/.env.production" ]]; then
        source environments/.env.production
        
        echo "配置对比:"
        echo "----------------------------------------"
        
        # 检查数据库配置
        echo "数据库配置对比:"
        echo "  环境文件 DB_HOST: $DB_HOST"
        if docker ps --filter "name=anxin-backend-prod" --format "{{.Names}}" | grep -q "anxin-backend-prod"; then
            container_db_host=$(docker exec anxin-backend-prod env | grep "^DB_HOST=" | cut -d'=' -f2)
            echo "  容器内 DB_HOST: $container_db_host"
            
            if [[ "$DB_HOST" == "$container_db_host" ]]; then
                log_success "  ✓ DB_HOST 配置一致"
            else
                log_error "  ✗ DB_HOST 配置不一致"
            fi
        fi
        
        echo ""
        echo "Redis配置对比:"
        echo "  环境文件 REDIS_HOST: $REDIS_HOST"
        if docker ps --filter "name=anxin-backend-prod" --format "{{.Names}}" | grep -q "anxin-backend-prod"; then
            container_redis_host=$(docker exec anxin-backend-prod env | grep "^REDIS_HOST=" | cut -d'=' -f2 || echo "未设置")
            echo "  容器内 REDIS_HOST: $container_redis_host"
            
            if [[ "$REDIS_HOST" == "$container_redis_host" ]]; then
                log_success "  ✓ REDIS_HOST 配置一致"
            else
                log_error "  ✗ REDIS_HOST 配置不一致"
            fi
        fi
        
        echo "----------------------------------------"
    fi
}

# 测试配置生效
test_config_effectiveness() {
    log_info "测试配置是否生效..."
    
    if docker ps --filter "name=anxin-backend-prod" --format "{{.Names}}" | grep -q "anxin-backend-prod"; then
        # 检查应用启动日志中的配置信息
        echo "应用启动日志中的配置信息:"
        echo "----------------------------------------"
        
        # 查找数据库连接信息
        if ./deploy.sh logs backend -e production --tail 100 | grep -i "jdbc:mysql" | tail -1; then
            log_success "✓ 找到数据库连接配置"
        else
            log_warn "未找到数据库连接配置"
        fi
        
        # 查找Redis连接信息
        if ./deploy.sh logs backend -e production --tail 100 | grep -i "redis" | tail -3; then
            log_success "✓ 找到Redis连接配置"
        else
            log_warn "未找到Redis连接配置"
        fi
        
        echo "----------------------------------------"
    fi
}

# 显示修复建议
show_fix_suggestions() {
    log_info "修复建议:"
    echo "========================================"
    echo "如果环境变量未正确加载，请按以下步骤操作:"
    echo ""
    echo "1. 完全重新创建容器:"
    echo "   ./deploy.sh down -e production"
    echo "   ./deploy.sh up -e production"
    echo ""
    echo "2. 检查环境文件是否被正确读取:"
    echo "   docker-compose -f docker-compose.production.yml --env-file environments/.env.production config | grep -A 5 -B 5 REDIS"
    echo ""
    echo "3. 手动验证环境变量:"
    echo "   docker exec anxin-backend-prod env | grep -E '^(DB_|REDIS_)'"
    echo ""
    echo "4. 如果仍有问题，检查docker-compose.yml中是否缺少环境变量定义"
    echo "========================================"
}

# 主函数
main() {
    log_info "环境变量检查工具"
    echo "========================================"
    
    check_env_file
    echo ""
    
    check_compose_config
    echo ""
    
    check_container_env
    echo ""
    
    compare_configs
    echo ""
    
    test_config_effectiveness
    echo ""
    
    show_fix_suggestions
    
    echo "========================================"
    log_success "检查完成!"
}

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