#!/bin/bash

# Laravel知识库系统 - 生产环境启动脚本

set -e

echo "🚀 启动Laravel知识库系统生产环境..."

# 检查必要文件
if [ ! -f ".env" ]; then
    echo "❌ 错误: .env文件不存在"
    echo "请复制.env.production为.env并配置相应参数"
    exit 1
fi

if [ ! -f "docker-compose.yml" ]; then
    echo "❌ 错误: docker-compose.yml文件不存在"
    exit 1
fi

# 创建必要的目录
echo "📁 创建存储目录..."
mkdir -p storage/mysql
mkdir -p storage/redis
mkdir -p storage/meilisearch
mkdir -p storage/logs/app
mkdir -p storage/logs/queue
mkdir -p storage/app/public
mkdir -p storage/app/documents
mkdir -p storage/app/markdown

# 设置目录权限
echo "🔐 设置目录权限..."
chmod -R 755 storage/
chmod -R 755 bootstrap/cache/

# 构建应用镜像
echo "🏗️ 构建Docker镜像..."
docker-compose build --no-cache app

# 启动服务
echo "🔄 启动服务..."
docker-compose up -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务状态
echo "🔍 检查服务状态..."
docker-compose ps

# 运行Laravel初始化命令
echo "🔧 运行Laravel初始化..."
docker-compose exec app php artisan key:generate --force
docker-compose exec app php artisan migrate --force
docker-compose exec app php artisan config:cache
docker-compose exec app php artisan route:cache
docker-compose exec app php artisan view:cache
docker-compose exec app php artisan storage:link

# 设置文件权限
echo "📝 设置应用权限..."
docker-compose exec app chown -R www-data:www-data /var/www/html/storage
docker-compose exec app chown -R www-data:www-data /var/www/html/bootstrap/cache

# 健康检查
echo "🏥 执行健康检查..."
sleep 10

# 检查Web应用 (Swoole)
if curl -f http://localhost:8000/health > /dev/null 2>&1; then
    echo "✅ Web应用健康检查通过"
else
    # 如果没有专门的健康检查路由，尝试访问根路径
    if curl -f http://localhost:8000/ > /dev/null 2>&1; then
        echo "✅ Web应用健康检查通过"
    else
        echo "❌ Web应用健康检查失败"
    fi
fi

# 检查MySQL
if docker-compose exec mysql mysqladmin ping -h localhost --silent; then
    echo "✅ MySQL健康检查通过"
else
    echo "❌ MySQL健康检查失败"
fi

# 检查Redis
if docker-compose exec redis redis-cli ping > /dev/null 2>&1; then
    echo "✅ Redis健康检查通过"
else
    echo "❌ Redis健康检查失败"
fi

# 检查Meilisearch
if curl -f http://localhost:7700/health > /dev/null 2>&1; then
    echo "✅ Meilisearch健康检查通过"
else
    echo "❌ Meilisearch健康检查失败"
fi

echo ""
echo "🎉 生产环境启动完成！"
echo ""
echo "📊 服务访问地址:"
echo "   Web应用: http://localhost:8000"
echo "   Meilisearch: http://localhost:7700"
echo ""
echo "🔧 管理命令:"
echo "   查看日志: docker-compose logs -f"
echo "   停止服务: docker-compose down"
echo "   重启服务: docker-compose restart"
echo "   查看状态: docker-compose ps"
echo ""