#!/bin/bash

# Octane HTTP服务器健康检查脚本
# 用于Docker健康检查，支持Swoole和RoadRunner

set -e

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

# 检查HTTP端口是否可访问
OCTANE_PORT=${OCTANE_PORT:-8000}
if ! curl -f -s "http://localhost:${OCTANE_PORT}/health" > /dev/null 2>&1; then
    echo "Octane HTTP服务器端口 ${OCTANE_PORT} 不可访问"
    exit 1
fi

# 检查Laravel应用是否可以连接到数据库和Redis
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();
    
    // 检查Redis连接
    if (config('cache.default') === 'redis') {
        \Illuminate\Support\Facades\Cache::store('redis')->put('octane_health_check', 'ok', 10);
        \Illuminate\Support\Facades\Cache::store('redis')->forget('octane_health_check');
    }
    
    echo 'OK';
} catch (Exception \$e) {
    echo 'ERROR: ' . \$e->getMessage();
    exit(1);
}
"; then
    echo "Octane服务器依赖服务检查失败"
    exit 1
fi

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