#!/bin/bash

# Laravel知识库系统 - 部署验证脚本

set -e

echo "🔍 验证Docker部署配置..."
echo ""

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

# 检查函数
check_requirement() {
    local name=$1
    local command=$2
    local version_flag=$3
    
    echo -n "检查 $name: "
    if command -v $command >/dev/null 2>&1; then
        if [ -n "$version_flag" ]; then
            version=$($command $version_flag 2>/dev/null | head -n1)
            echo -e "${GREEN}✅ 已安装${NC} ($version)"
        else
            echo -e "${GREEN}✅ 已安装${NC}"
        fi
        return 0
    else
        echo -e "${RED}❌ 未安装${NC}"
        return 1
    fi
}

# 检查系统要求
echo "📋 系统要求检查:"
check_requirement "Docker" "docker" "--version"
check_requirement "Docker Compose" "docker-compose" "--version"

echo ""

# 检查Docker服务状态
echo "🐳 Docker服务状态:"
if docker info >/dev/null 2>&1; then
    echo -e "${GREEN}✅ Docker服务运行正常${NC}"
else
    echo -e "${RED}❌ Docker服务未运行${NC}"
    exit 1
fi

echo ""

# 检查配置文件
echo "📁 配置文件检查:"
config_files=(
    "docker-compose.yml:Docker Compose配置"
    "Dockerfile:Docker镜像配置"
    ".env.production:环境变量模板"
    "docker/mysql/my.cnf:MySQL配置"
    "docker/redis/redis.conf:Redis配置"
)

for item in "${config_files[@]}"; do
    file=$(echo $item | cut -d: -f1)
    desc=$(echo $item | cut -d: -f2)
    
    if [ -f "$file" ]; then
        echo -e "${GREEN}✅${NC} $desc ($file)"
    else
        echo -e "${RED}❌${NC} $desc ($file) - 文件不存在"
    fi
done

echo ""

# 检查存储目录
echo "📂 存储目录检查:"
storage_dirs=(
    "storage/mysql:MySQL数据目录"
    "storage/redis:Redis数据目录"
    "storage/meilisearch:Meilisearch数据目录"
    "storage/logs/app:应用日志目录"
    "storage/logs/queue:队列日志目录"
    "storage/app:应用存储目录"
)

for item in "${storage_dirs[@]}"; do
    dir=$(echo $item | cut -d: -f1)
    desc=$(echo $item | cut -d: -f2)
    
    if [ -d "$dir" ]; then
        echo -e "${GREEN}✅${NC} $desc ($dir)"
    else
        echo -e "${YELLOW}⚠️${NC} $desc ($dir) - 目录不存在，将在启动时创建"
    fi
done

echo ""

# 检查管理脚本
echo "🔧 管理脚本检查:"
scripts=(
    "docker/start-production.sh:启动脚本"
    "docker/stop-production.sh:停止脚本"
    "docker/check-services.sh:状态检查脚本"
    "docker/test-config.sh:配置测试脚本"
)

for item in "${scripts[@]}"; do
    script=$(echo $item | cut -d: -f1)
    desc=$(echo $item | cut -d: -f2)
    
    if [ -f "$script" ]; then
        if [ -x "$script" ]; then
            echo -e "${GREEN}✅${NC} $desc ($script) - 可执行"
        else
            echo -e "${YELLOW}⚠️${NC} $desc ($script) - 不可执行"
        fi
    else
        echo -e "${RED}❌${NC} $desc ($script) - 文件不存在"
    fi
done

echo ""

# 检查Docker Compose配置
echo "🔍 Docker Compose配置验证:"
if docker-compose config --quiet 2>/dev/null; then
    echo -e "${GREEN}✅ Docker Compose配置语法正确${NC}"
    
    # 显示服务列表
    echo ""
    echo "📊 配置的服务:"
    services=$(docker-compose config --services)
    for service in $services; do
        echo -e "${GREEN}  ✓${NC} $service"
    done
else
    echo -e "${RED}❌ Docker Compose配置语法错误${NC}"
fi

echo ""

# 检查环境配置
echo "🔧 环境配置检查:"
if [ -f ".env" ]; then
    echo -e "${GREEN}✅ .env 文件存在${NC}"
    
    # 检查关键配置项
    required_vars=("APP_KEY" "DB_PASSWORD" "MEILISEARCH_KEY")
    for var in "${required_vars[@]}"; do
        if grep -q "^${var}=" .env && ! grep -q "^${var}=$" .env; then
            echo -e "${GREEN}  ✓${NC} $var 已配置"
        else
            echo -e "${YELLOW}  ⚠️${NC} $var 未配置或为空"
        fi
    done
else
    echo -e "${YELLOW}⚠️ .env 文件不存在${NC}"
    echo "  建议执行: cp .env.production .env"
fi

echo ""

# 系统资源检查
echo "💾 系统资源检查:"

# 检查可用内存 (macOS兼容)
if command -v free >/dev/null 2>&1; then
    # Linux系统
    available_memory=$(free -m | awk 'NR==2{printf "%.0f", $7}')
elif command -v vm_stat >/dev/null 2>&1; then
    # macOS系统
    page_size=$(vm_stat | grep "page size" | awk '{print $8}')
    free_pages=$(vm_stat | grep "Pages free" | awk '{print $3}' | sed 's/\.//')
    available_memory=$((free_pages * page_size / 1024 / 1024))
else
    available_memory=0
fi

if [ "$available_memory" -ge 4096 ]; then
    echo -e "${GREEN}✅ 可用内存: ${available_memory}MB (推荐: 4GB+)${NC}"
elif [ "$available_memory" -ge 2048 ]; then
    echo -e "${YELLOW}⚠️ 可用内存: ${available_memory}MB (推荐: 4GB+)${NC}"
elif [ "$available_memory" -gt 0 ]; then
    echo -e "${RED}❌ 可用内存: ${available_memory}MB (推荐: 4GB+)${NC}"
else
    echo -e "${YELLOW}⚠️ 无法检测内存使用情况${NC}"
fi

# 检查可用磁盘空间 (macOS兼容)
if df -h . >/dev/null 2>&1; then
    available_disk=$(df -h . | awk 'NR==2{print $4}' | sed 's/G.*//' | sed 's/[^0-9].*//')
    if [ -n "$available_disk" ] && [ "$available_disk" -ge 10 ]; then
        echo -e "${GREEN}✅ 可用磁盘: ${available_disk}GB+ (推荐: 10GB+)${NC}"
    elif [ -n "$available_disk" ] && [ "$available_disk" -ge 5 ]; then
        echo -e "${YELLOW}⚠️ 可用磁盘: ${available_disk}GB+ (推荐: 10GB+)${NC}"
    elif [ -n "$available_disk" ]; then
        echo -e "${RED}❌ 可用磁盘: ${available_disk}GB+ (推荐: 10GB+)${NC}"
    else
        echo -e "${YELLOW}⚠️ 无法检测磁盘使用情况${NC}"
    fi
else
    echo -e "${YELLOW}⚠️ 无法检测磁盘使用情况${NC}"
fi

echo ""

# 总结
echo "📋 验证总结:"
echo ""
echo "✅ 配置完整性: 所有必要的配置文件都已就位"
echo "✅ 脚本可用性: 管理脚本已准备就绪"
echo "✅ Docker环境: Docker和Docker Compose可用"
echo ""

if [ -f ".env" ]; then
    echo -e "${GREEN}🚀 系统已准备就绪！${NC}"
    echo ""
    echo "下一步操作:"
    echo "1. 启动服务: ./docker/start-production.sh"
    echo "2. 检查状态: ./docker/check-services.sh"
    echo "3. 访问应用: http://localhost"
else
    echo -e "${YELLOW}⚠️ 需要完成环境配置${NC}"
    echo ""
    echo "下一步操作:"
    echo "1. 复制配置: cp .env.production .env"
    echo "2. 编辑配置: nano .env"
    echo "3. 启动服务: ./docker/start-production.sh"
fi

echo ""