<?php

// check env
$err = false;
if ( !function_exists("posix_getpid") ) {
    $err = true;
    printf("Require posix_getpid , try yum install php-process\n");
}

if ( $err ) {
    exit;
}
error_reporting(0);

$host['ip'] = "xga.x-legend.com";
$host['port'] = "9050";
$cfg = array(
    "game" => "M7HK",
    "server" => "1",
    "topic" => "test.log"
);

$flag = array();
$k = md5(serialize($host));
if (file_exists(sprintf("/tmp/clog_%s", $k))) {
    $fp = fopen(sprintf("/tmp/clog_%s", $k), "r");
    while (!feof($fp)) {
        $l = fgets($fp, 8192);
    }
} else {
    $l = "{}";
}

$config = json_decode($l, true);


$file_pid = sprintf("/tmp/clog_%s.pid",$k); 
$f = @file($file_pid);
if ( $f[0] != '' ) {
  if ( posix_getsid($f[0]) ) {
    printf("Process %s already exists\r\n",$f[0]);
    exit();
  }
}
$pid = posix_getpid();
$pfp = fopen($file_pid,"w");
fputs($pfp,$pid);
fclose($pfp);


$timer = 0;
while (true) {
    if (time() - $timer > 300) {
        $timer = time();
        print "flush filelist\n";
        foreach ($config as $fn => $row) {
            // 重新檢查檔案是否存在，不存在就將他移出 queue
            if (!file_exists($fn)) {
                unset($config[$fn]);
            }
        }
        // 每分鐘從新整理一次 filelist
        $r = filelist($_SERVER['HOME'], ".+level\.log.+");
        foreach ($r as $k => $v) {
            if (preg_match("/\/servers(\d+)\/[a-z]+(\d+)\/(.+)$/i", $v, $a)) {
                if (!key_exists($v, $config)) {
                    $config[$v] = array(
                        "server" => $a[2],
                        "filename" => $a[3],
                        "pos" => 0
                    );
                }

                // 重新開啟 file handler，為了能看到檔案後續新增的內容
                if (is_resource($config[$v]['fp'])) {
                    fclose($fp);
                }
                // reopen
                $config[$v]['fp'] = fopen($v, "r");
                fseek($config[$v]['fp'], $config[$v]['pos']);

                if (!is_resource($config[$v]['sp'])) {
                    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
                    if (socket_connect($socket, $host['ip'], $host['port'])) {
                        $cfg['server'] = $config[$v]['server'];
                        $cfg['topic'] = $config[$v]['filename'];
                        socket_write($socket, json_encode($cfg) . "\n");
                        $config[$v]['sp'] = $socket;
                        printf("Connect to server %s:%s success\n",$host['ip'],$host['port']);
                    } else {
                        printf("Can't connect to server %s:%s\n",$host['ip'],$host['port']);
                    }
                }
            }
        }
    }

    foreach ($config as $k => $row) {
        $fp = $row['fp'];
        $socket = $row['sp'];

        if (is_resource($socket)) {
            while (!feof($fp)) {
                $pos = ftell($fp);
                $l = fread($fp, 4096);
                if ( strlen($l) > 0 ) {
                    if (!socket_send($socket, $l, strlen($l), MSG_EOR)) {
                        // server disconnect
                        print "Server disconnect\n";
                        $config[$k]['sp'] = '';
                        fseek($fp, $pos);
                        break 1;
                    }
                }
            }
        }
        $config[$k]['pos'] = ftell($fp);
    }

    $fp2 = fopen(sprintf("/tmp/clog_%s", md5(serialize($host))), "w");
    fputs($fp2, json_encode($config));
    fclose($fp2);

    sleep(5);
}

exit;
foreach ($r as $k => $v) {

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_connect($socket, $host['ip'], $host['port']);
    socket_write($socket, json_encode($cfg) . "\n");
}

foreach ($r as $k => $v) {
    while (!feof($fp)) {
        $i++;
        $l = fgets($fp);
        socket_send($socket, $l, strlen($l), MSG_EOR);
    }
}

function filelist($path, $pattern) {
    $ret = array();
    $d = dir($path);
    while (false !== ($entry = $d->read())) {
        if ($entry == '.' || $entry == '..' || $entry == 'Log')
            continue;

        $pp = realpath($path . "/" . $entry);

        if (is_dir($pp)) {
            $ret = array_merge($ret, filelist($pp, $pattern));
        } else {
            if (preg_match("/" . $pattern . "/", $entry)) {
                $ret[] = realpath(sprintf("%s/%s", $path, $entry));
            }
        }
    }

    return $ret;
}

