<?php
define("APPLICATION_PATH", realpath(dirname(__FILE__) . '/../../../')); //指向public的上一级
require APPLICATION_PATH . '/scripts/crontab/baseCli.php';
require APPLICATION_PATH . '/scripts/crontab/common.php';
error_reporting(E_ALL ^ E_NOTICE);
class runRedisPush
{
    /* config */
    const LISTEN = "tcp://192.168.2.15:5555";
    const MAXCONN = 100;
    const pidfile = __CLASS__;
    const uid = 80;
    const gid = 80;
    /**/
    protected $pool = NULL;
    protected $zmq = NULL;

    public function __construct()
    {
        $this->pidfile = '/var/run/' . self::pidfile . '.pid';
    }

    private function daemon()
    {
        if (file_exists($this->pidfile)) {
            echo "The file $this->pidfile exists.\n";
            exit();
        }

        $pid = pcntl_fork();
        if ($pid == -1) {
            die('could not fork');
        } else if ($pid) {
// we are the parent
//pcntl_wait($status); //Protect against Zombie children
            exit($pid);
        } else {
// we are the child
            file_put_contents($this->pidfile, getmypid());
            posix_setuid(self::uid);
            posix_setgid(self::gid);
            return (getmypid());
        }
    }
    public function callback($instance,$channelName,$message){
        try{
            $message=json_decode($message,true);
            $callInstance=$message['className']::getInstance(\Our\DbNameConst::masterDBConnectName);
            echo json_encode($message)."\r\n";
            if(empty($message['params'])){
                $res=call_user_func_array(array($callInstance,$message['method']),array());
            }else{
                $res=call_user_func_array(array($callInstance,$message['method']),$message['params']);
            }
            $res=(isset($res)&&!empty($res))?$res:false;
            if($res!==false){
                echo 'success'."\r\n";
            }else{
                echo 'fail1'."\r\n";
            }
            unset($callInstance);
            \Mysql\LinkMySQLModel::unsetDbConecet();
        }catch(Exception $ex){
            echo $ex->getMessage();
        }
//        $orderService=\Business\Order\OrderServiceModel::getInstance();
//        $orderService->testPush($message);
    }
    protected function status(){
        if (file_exists($this->pidfile)) {
            $pid = file_get_contents($this->pidfile);
            printf("%s already running, pid = %s\n", $this->argv[0], $pid);
        }else{
            printf("%s haven't running\n", $this->argv[0]);
        }
    }
    private function start()
    {
        $pid = $this->daemon();
        $conf = \Yaf\Registry::get('config')->get('redis.database.params');
        $redisPublishName=\Yaf\Registry::get('config')->get('redis.redisPublishName');
        $redis=new Redis();
        $redis->connect($conf['host'], $conf['port']);
        if(!empty($conf['password'])){
            $redis->auth($conf['password']);
        }
//ini_set('default_socket_timeout', -1);(所有长连接不超时)
        $redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
        $result=$redis->subscribe(array($redisPublishName), array($this,'callback'));

    }
    private function reload(){
        if (file_exists($this->pidfile)) {
            $pid = file_get_contents($this->pidfile);
            posix_kill($pid, SIGUSR1);
            exit;
            //posix_kill(posix_getpid(), SIGHUP);
           // posix_kill($pid, SIGHUP);
        }
    }
    protected function restart(){
        $this->stop();
        $this->start();
    }

    private function stop()
    {

        if (file_exists($this->pidfile)) {
            $pid = file_get_contents($this->pidfile);
            posix_kill($pid, 9);
            unlink($this->pidfile);
        }
    }

    private function help($proc)
    {
        printf("%s start | stop | help | restart | reload \n", $proc);
    }
    private $argv;
    public function main($argv)
    {
        $this->argv=$argv;
        if (count($argv) < 2) {
            printf("please input help parameter\n");
            exit();
        }
        if ($argv[1] === 'stop') {

            $this->stop();
        } else if ($argv[1] === 'start') {
            $this->start();
        } else if($argv[1] === 'restart'){
            $this->restart();
        }else if($argv[1] === 'status'){
            $this->status();
        }else if($argv[1]==='reload'){
            $this->reload();
        }
        else{
            $this->help($argv[0]);
        }
    }
}

$cgse = new runRedisPush();
$cgse->main($argv);