<?php

use Api\PhpServices\Daemon\Daemon;
use App\Base\Cli;
use Yaf\Application;


/**
 * 守护进程入口脚本
 * conf/cli.ini 中配置脚本目录，默认在 /daemon
 * 脚本必须继承 DaemonServiceInterface，参考 daemon/Test.php
 * 以守护进程方式执行 Test 脚本命令参考：php public/cli.php daemon run "t=Test&n=2&j=abc"
 *      t : 脚本类名
 *      n : 进程数
 *      j : 进程别名，默认为脚本类名
 */
class DaemonController extends Cli
{
    public function RunAction(){
        $request = $this->getRequest();
        $params  = $request->getParams();

        $task_name  = $params['t'] ?? "";
        $worker_num = $params['n'] ?? 4;
        $rename     = $params['j'] ?? $task_name;

        if(empty($task_name)){
            echo <<<EOD

usage: php cli.php daemon run "t=[string]&n=[int|default:4]&j=[string]"
        t   daemo 脚本类名
        n   进程数
        j   进程别名，默认同脚本类名
stop : kill -SIGUSR1 master进程id\n

EOD;
            return;
        }

        $script_dir = Application::app()->getConfig()->get("daemon.script_dir");
        $task_class = $script_dir.$task_name;

        if(!class_exists($task_class)){
            die("脚本不存在！");
        }

        $check = new ReflectionClass($task_class);
        if(!$check->implementsInterface('Api\PhpServices\Daemon\DaemonServiceInterface')){
            die("脚本需实现 DaemonServiceInterface 接口！");
        }

        (new Daemon($rename, $task_class, $worker_num))->start();
    }
}