<?php
/**
 * 监控器程序模板，一个站点生成一个
 */
$runSpider = $argv[1];
$process = `ps aux | grep Monitor$runSpider | grep -v grep | grep -v sh | wc -l`;
$process = intval($process);
if ($process > 1)
{
    exit;
}

require 'init.php';

$GLOBALS['db']->delete(CollectLock::table())->where(array('site'=>$runSpider))->q();

$class = Spider::getClass($runSpider);
if (!$class::isContinuance())
{
    // 非持久运行的
    $updateList = call_user_func_array(array($class, 'getNewList'), array());
    if (empty($updateList))
    {
        // 没获取到列表，直接退出
        exit;
    }
    
    foreach ($updateList as $key => $value)
    {
        $inNames[] = "'".mysql_real_escape_string(trim($value))."'";
    }
    $sql = "SELECT bookid, bookname FROM " . Book::table()." WHERE status = 0 AND bookname IN (".implode(',', $inNames).')';
    $result = $GLOBALS['db']->setQueryString($sql)->find();
    
    foreach ($result as $book)
    {
        foreach ($updateList as $key => $value)
        {
            if ($book['bookname'] == $value)
            {
                updateBook($book['bookid'], $runSpider, $key);
            }
        }
    }
    
    if ($class::isFetchNew() && count($updateList) > count($result))
    {
        // 列表里的书本站不存在，尝试抓取新书
        addNewBook($updateList);
        msg("完毕，进入下一轮监控\n");
        exit;
    }
    
    exit;
}

// 持久运行的
do
{
    //$updateList = call_user_func_array(array($class, 'getNewList'));
}while(true);