<?php

function autoSyncJob() {
 global $channelInfoNew, $globalsettings;

  if (realForwardCount() != 0) { 
   logger("job: autoSync - forwardqueue is not empty, skip turn");
   return;
  } // if (realForwardCount() != 0) 

  logger("job: autoSync - start");

  unset($breakout);

  foreach(array_keys($channelInfoNew) as $channelInfoKey) {
   unset ($filesleft);
   if ($channelInfoNew[$channelInfoKey]["status"] == "ok" && $channelInfoNew[$channelInfoKey]["autosync"] != -1 ) {
    if (isset($breakout)) { break; }
    $source=$channelInfoKey;
    if (!array_key_exists("-1", $channelInfoNew[$channelInfoKey]["to"])) { 
     foreach (array_keys($channelInfoNew[$channelInfoKey]["to"]) as $to ) {

	  if (array_key_exists($channelInfoNew[$channelInfoKey]["to"][$to]["chanid"], $channelInfoNew)) {
 	   if ($channelInfoNew[$channelInfoNew[$channelInfoKey]["to"][$to]["chanid"]]["disabled"] != -1) break;
	   if ($channelInfoNew[$channelInfoNew[$channelInfoKey]["to"][$to]["chanid"]]["disabled"] == 2) break; // updatedb
	  }	  

      if ($channelInfoNew[$channelInfoKey]["from_topic_id"] != -1 ) { $topicclausel=" and topic_id = ".$channelInfoNew[$channelInfoKey]["from_topic_id"]." "; } else $topicclausel="";

      $fileslefthead="set local enable_seqscan = off;
                      select count(*) as count ";

      $sqlbody="            
            from chan_".$channelInfoNew[$channelInfoKey]["chanid"]." t1 
            where 
            ".typeclausel($channelInfoNew[$channelInfoKey]["typemapping"])." 
            ".$topicclausel."
            and 
             not exists (select * from chan_".$channelInfoNew[$channelInfoKey]["to"][$to]["chanid"]." t2 
                         where
                          t2.width = t1.width
                         and
                          t2.height = t1.height
                         and
                          t2.duration  = t1.duration
                         and
                          t2.filedate between t1.filedate-5 and t1.filedate+5 
                         and
                          t2.size  = t1.size
                         )"; // -- between, tolerance during data inconsistens @ tg 
                         
     $sql=$fileslefthead.$sqlbody.";";

     $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
     while ($row = pg_fetch_array($result)) $filesleft=$row['count'];
     if (!isset($filesleft)) $filesleft=0;

     if ($channelInfoNew[$channelInfoKey]["autosync"]== 1 || $channelInfoNew[$channelInfoKey]["autosync"]== -1) $sqllimit=" limit 20;";  
	 if ($channelInfoNew[$channelInfoKey]["autosync"]== 2) $sqllimit=" ;";

     $sql="set local enable_seqscan = off;
           select msgid, message, substr(cleanmessage, 0, ".$globalsettings["message"]["cuttext"].") as cleanmessage, duration, grouped_id, filedate, size, width, height, topic_id ".$sqlbody;
     $sql.=" order by msgid asc ".$sqllimit;

     if ($filesleft != 0 ) { 
      $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
      $numrows=pg_num_rows($result);
      logger("job: autoSync - from: [".$channelInfoNew[$channelInfoKey]["name"]."] to: [".$channelInfoNew[$channelInfoKey]["to"][$to]["name"]."] files left: ".$filesleft."");
      $target=$channelInfoNew[$channelInfoKey]["to"][$to]["chanid"];
      $breakout=true;
      break;
     } else { 
	  $channelInfoNew[$channelInfoKey]["autosync"] = -1; 
	  logger("job: autoSync - from: [".$channelInfoNew[$channelInfoKey]["name"]."] to: [".$channelInfoNew[$channelInfoKey]["to"][$to]["name"]."] in sync, autosync for these channels disabled for session");
	 } // if ($numrows != 0) // disable autosync when channel in sync for these session
    } // foreach (array_keys($channelInfoNew[$k]["to"]) as $to )
   } // if (!array_key_exists("-1", $channelInfoNew[$channelInfoKey]["to"])) 
  } // if ($channelInfoNew[$channelInfoKey]["status"] == "ok" && $channelInfoNew[$channelInfoKey]["autosync"] != -1 )
 } // foreach(array_keys($channelInfoNew) as $channelInfoKey)

 if (isset($breakout)) {
  syncFiles(-1, $source, $result);
  return;
 } // if (isset($breakout) 

 if (!isset($breakout)) {
  logger("job: autoSync - all configured channels in sync");
  return;
 } // if (!isset($breakout) 

 return;
} // function end