#!/bin/bash

# 数据持久化测试脚本
# 验证所有数据卷映射是否正确配置

set -e

echo "开始测试数据持久化配置..."

# 检查存储目录是否存在
check_directory() {
    local dir=$1
    local description=$2
    
    if [ -d "$dir" ]; then
        echo "✓ $description 目录存在: $dir"
        return 0
    else
        echo "✗ $description 目录不存在: $dir"
        return 1
    fi
}

# 检查docker-compose配置中的卷映射
check_volume_mapping() {
    local volume_name=$1
    local description=$2
    
    if docker-compose config | grep -q "$volume_name"; then
        echo "✓ $description 卷映射已配置: $volume_name"
        return 0
    else
        echo "✗ $description 卷映射未配置: $volume_name"
        return 1
    fi
}

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

# 检查所有必要的存储目录
check_directory "storage/mysql" "MySQL数据库存储"
check_directory "storage/redis" "Redis缓存存储"
check_directory "storage/meilisearch" "Meilisearch搜索存储"
check_directory "storage/app" "Laravel应用存储"
check_directory "storage/app/private/documents" "文档上传存储"
check_directory "storage/app/public" "公共文件存储"
check_directory "storage/logs" "日志存储"
check_directory "storage/logs/app" "应用日志存储"
check_directory "storage/logs/queue" "队列日志存储"

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

# 检查所有卷映射配置
check_volume_mapping "mysql_data" "MySQL数据"
check_volume_mapping "redis_data" "Redis数据"
check_volume_mapping "meilisearch_data" "Meilisearch数据"
check_volume_mapping "storage_data" "应用存储数据"
check_volume_mapping "documents_data" "文档存储数据"
check_volume_mapping "public_data" "公共文件数据"
check_volume_mapping "app_logs" "应用日志"
check_volume_mapping "queue_logs" "队列日志"
check_volume_mapping "laravel_logs" "Laravel日志"

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

# 检查关键目录的权限
for dir in storage/mysql storage/redis storage/meilisearch storage/app storage/logs; do
    if [ -d "$dir" ]; then
        perms=$(stat -f "%A" "$dir" 2>/dev/null || stat -c "%a" "$dir" 2>/dev/null || echo "unknown")
        echo "✓ $dir 权限: $perms"
    fi
done

echo ""
echo "数据持久化配置测试完成！"

# 创建测试文件验证映射
echo ""
echo "创建测试文件验证目录映射..."

test_file="storage/app/test-persistence-$(date +%s).txt"
echo "测试数据持久化配置 - $(date)" > "$test_file"

if [ -f "$test_file" ]; then
    echo "✓ 测试文件创建成功: $test_file"
    rm "$test_file"
    echo "✓ 测试文件清理完成"
else
    echo "✗ 测试文件创建失败"
    exit 1
fi

echo ""
echo "所有数据持久化配置检查通过！"