<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Dotenv\Dotenv;

require_once __DIR__ . '/vendor/autoload.php';
// 加载.env文件
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$worker = new Worker('http://0.0.0.0:8787');

$worker->onConnect = function ($connection) {
    echo "New connection\n";
};

$worker->onMessage = function(TcpConnection $connection, Request $request)
{
    $work_dir = isset($_ENV['WORK_DIR']) ? $_ENV['WORK_DIR'] : null;
    $branch = isset($_ENV['BRANCH']) ? $_ENV['BRANCH'] : null;
    var_dump($request->post());

    if ($work_dir && $branch) {
        // chdir($work_dir);
        // exec("git fetch origin $branch");
        // exec("git reset --hard FETCH_HEAD");

        // exec("yarn install");
        // exec("yarn build");

        // $connection->send("Deployment finished\n");
        // $connection->close();
    }

    // 设置工作目录
    // $WORK_DIR = "/www/wwwroot/fs.book.wandoubaba.com";

    // 设置远程仓库地址
    // $REMOTE_REPO = "git@git.wandoubaba.com:wandoubaba/knowledge.git";

    // 设置分支名称
    // $BRANCH = "master";

    // 验证请求是否合法
    // $secret = "your-webhook-secret";
    // $signature = $_SERVER['HTTP_X_HUB_SIGNATURE'] ?? '';
    // $body = $data;
    // if (!hash_equals('sha1=' . hash_hmac('sha1', $body, $secret), $signature)) {
    //     $connection->send("Invalid request\n");
    //     $connection->close();
    //     return;
    // }

    // // 切换到工作目录
    // chdir($WORK_DIR);

    // // 拉取最新代码
    // exec("git fetch origin $BRANCH");
    // exec("git reset --hard FETCH_HEAD");

    // // 执行相关命令
    // exec("yarn install");
    // exec("yarn build");

    // $connection->send("Deployment finished\n");
    // $connection->close();
};

// 运行worker
Worker::runAll();