#!/bin/sh

# Swoole HTTP服务器健康检查脚本
# 用于Docker健康检查

set -e

# 检查Swoole进程是否运行
if ! pgrep -f "octane:start" > /dev/null; then
    echo "Swoole HTTP服务器进程未运行"
    exit 1
fi

# 检查HTTP服务是否响应
if ! curl -f -s http://localhost:8000/health > /dev/null 2>&1; then
    # 如果没有专门的健康检查路由，尝试访问根路径
    if ! curl -f -s http://localhost:8000/ > /dev/null 2>&1; then
        echo "Swoole HTTP服务器无响应"
        exit 1
    fi
fi

# 检查Laravel应用是否可以连接到数据库和缓存
if ! php -r "
try {
    require_once '/var/www/html/vendor/autoload.php';
    \$app = require_once '/var/www/html/bootstrap/app.php';
    \$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
    
    // 检查数据库连接
    \Illuminate\Support\Facades\DB::connection()->getPdo();
    
    // 检查缓存连接
    \Illuminate\Support\Facades\Cache::put('swoole_health_check', 'ok', 10);
    \Illuminate\Support\Facades\Cache::forget('swoole_health_check');
    
    echo 'OK';
} catch (Exception \$e) {
    echo 'ERROR: ' . \$e->getMessage();
    exit(1);
}
"; then
    echo "Swoole服务器依赖服务检查失败"
    exit 1
fi

echo "Swoole HTTP服务器健康检查通过"
exit 0