#!/bin/bash

# 数据持久化配置验证脚本
# 全面验证Docker部署中的存储配置

set -e

echo "=========================================="
echo "数据持久化和目录映射配置验证"
echo "=========================================="

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

# 成功和失败计数
SUCCESS_COUNT=0
FAIL_COUNT=0

# 检查函数
check_success() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓${NC} $1"
        ((SUCCESS_COUNT++))
        return 0
    else
        echo -e "${RED}✗${NC} $1"
        ((FAIL_COUNT++))
        return 1
    fi
}

echo ""
echo "1. 检查存储目录结构..."
echo "----------------------------------------"

# 检查所有必要的存储目录
directories=(
    "storage/mysql:MySQL数据库存储目录"
    "storage/redis:Redis缓存存储目录"
    "storage/meilisearch:Meilisearch搜索存储目录"
    "storage/app:Laravel应用存储目录"
    "storage/app/private:私有文件存储目录"
    "storage/app/private/documents:文档上传存储目录"
    "storage/app/private/markdown:Markdown文件存储目录"
    "storage/app/public:公共文件存储目录"
    "storage/framework:Laravel框架缓存目录"
    "storage/framework/cache:缓存目录"
    "storage/framework/sessions:会话目录"
    "storage/framework/views:视图缓存目录"
    "storage/logs:日志存储目录"
    "storage/logs/app:应用日志存储目录"
    "storage/logs/queue:队列日志存储目录"
)

for dir_info in "${directories[@]}"; do
    IFS=':' read -r dir desc <<< "$dir_info"
    [ -d "$dir" ]
    check_success "$desc: $dir"
done

echo ""
echo "2. 检查Docker Compose卷映射配置..."
echo "----------------------------------------"

# 检查docker-compose.yml中的卷映射
volumes=(
    "mysql_data:MySQL数据卷"
    "redis_data:Redis数据卷"
    "meilisearch_data:Meilisearch数据卷"
    "storage_data:应用存储数据卷"
    "documents_data:文档存储数据卷"
    "public_data:公共文件数据卷"
    "app_logs:应用日志卷"
    "queue_logs:队列日志卷"
    "laravel_logs:Laravel日志卷"
)

for volume_info in "${volumes[@]}"; do
    IFS=':' read -r volume desc <<< "$volume_info"
    docker-compose config 2>/dev/null | grep -q "$volume" 
    check_success "$desc: $volume"
done

echo ""
echo "3. 检查服务容器的卷映射..."
echo "----------------------------------------"

# 检查应用容器的卷映射
app_volumes=(
    "./:/var/www/html:项目代码目录映射"
    "storage_data:/var/www/html/storage:应用存储目录映射"
    "documents_data:/var/www/html/storage/app/private/documents:文档存储目录映射"
    "public_data:/var/www/html/storage/app/public:公共文件目录映射"
    "app_logs:/var/log:应用日志目录映射"
    "laravel_logs:/var/www/html/storage/logs:Laravel日志目录映射"
)

for volume_info in "${app_volumes[@]}"; do
    IFS=':' read -r volume_mapping path desc <<< "$volume_info"
    docker-compose config 2>/dev/null | grep -q "$volume_mapping"
    check_success "应用容器 - $desc"
done

# 检查队列容器的卷映射
queue_volumes=(
    "./:/var/www/html:项目代码目录映射"
    "storage_data:/var/www/html/storage:应用存储目录映射"
    "documents_data:/var/www/html/storage/app/private/documents:文档存储目录映射"
    "public_data:/var/www/html/storage/app/public:公共文件目录映射"
    "queue_logs:/var/log:队列日志目录映射"
    "laravel_logs:/var/www/html/storage/logs:Laravel日志目录映射"
)

for volume_info in "${queue_volumes[@]}"; do
    IFS=':' read -r volume_mapping path desc <<< "$volume_info"
    docker-compose config 2>/dev/null | grep -q "$volume_mapping"
    check_success "队列容器 - $desc"
done

echo ""
echo "4. 检查数据卷绑定配置..."
echo "----------------------------------------"

# 检查bind mount配置
bind_mounts=(
    "storage/mysql:MySQL数据绑定"
    "storage/redis:Redis数据绑定"
    "storage/meilisearch:Meilisearch数据绑定"
    "storage/app:应用存储绑定"
    "storage/logs/app:应用日志绑定"
    "storage/logs/queue:队列日志绑定"
    "storage/logs:Laravel日志绑定"
)

for mount_info in "${bind_mounts[@]}"; do
    IFS=':' read -r mount_path desc <<< "$mount_info"
    # 检查相对路径或绝对路径
    if docker-compose config 2>/dev/null | grep -q "device:.*$mount_path" || docker-compose config 2>/dev/null | grep -q "device: ./$mount_path"; then
        check_success "$desc: $mount_path"
    else
        echo -e "${RED}✗${NC} $desc: $mount_path"
        ((FAIL_COUNT++))
    fi
done

echo ""
echo "5. 检查目录权限..."
echo "----------------------------------------"

# 检查关键目录的权限
permission_dirs=(
    "storage/mysql"
    "storage/redis"
    "storage/meilisearch"
    "storage/app"
    "storage/logs"
)

for dir in "${permission_dirs[@]}"; do
    if [ -d "$dir" ]; then
        perms=$(stat -f "%A" "$dir" 2>/dev/null || stat -c "%a" "$dir" 2>/dev/null || echo "unknown")
        if [ "$perms" = "755" ] || [ "$perms" = "unknown" ]; then
            check_success "$dir 权限正确: $perms"
        else
            echo -e "${YELLOW}⚠${NC} $dir 权限可能需要调整: $perms"
        fi
    else
        echo -e "${RED}✗${NC} $dir 目录不存在"
        ((FAIL_COUNT++))
    fi
done

echo ""
echo "6. 验证配置文件语法..."
echo "----------------------------------------"

# 验证docker-compose.yml语法
docker-compose config --quiet 2>/dev/null
check_success "Docker Compose配置文件语法正确"

echo ""
echo "7. 创建测试文件验证写入权限..."
echo "----------------------------------------"

# 测试各个存储目录的写入权限
test_dirs=(
    "storage/app:应用存储目录"
    "storage/logs:日志存储目录"
    "storage/mysql:MySQL存储目录"
    "storage/redis:Redis存储目录"
    "storage/meilisearch:Meilisearch存储目录"
)

for dir_info in "${test_dirs[@]}"; do
    IFS=':' read -r dir desc <<< "$dir_info"
    test_file="$dir/test-write-$(date +%s).tmp"
    
    if echo "test" > "$test_file" 2>/dev/null; then
        rm -f "$test_file" 2>/dev/null
        check_success "$desc 写入权限正常"
    else
        echo -e "${RED}✗${NC} $desc 写入权限异常"
        ((FAIL_COUNT++))
    fi
done

echo ""
echo "=========================================="
echo "验证结果汇总"
echo "=========================================="

echo -e "成功检查项: ${GREEN}$SUCCESS_COUNT${NC}"
echo -e "失败检查项: ${RED}$FAIL_COUNT${NC}"

if [ $FAIL_COUNT -eq 0 ]; then
    echo -e "\n${GREEN}🎉 所有数据持久化配置检查通过！${NC}"
    echo "系统已准备好进行Docker部署。"
    exit 0
else
    echo -e "\n${RED}❌ 发现 $FAIL_COUNT 个配置问题，请修复后重新验证。${NC}"
    exit 1
fi