<?php

$destDir = '/data/violet';
$srcDir  = '/srv/www/violet/web';
$infoDir = '/srv/www/violet/web/uploads/previews/upinfo';
$logFile = '/var/log/synch/synch.log';
$posFiles = array(
    '/var/log/synch/resources.pos',
    '/var/log/synch/blogs.pos',
    '/var/log/synch/thumbnails.pos'
);

$options = getopt('i');
$ignore = array_key_exists('i', $options);

foreach ($posFiles as $posFile) {
  do {
    $fh = fopen($posFile, 'r');
    $name = trim(fgets($fh));
    $index = trim(fgets($fh));
    $pointer = trim(fgets($fh));
    fclose($fh);

    $listFile = $infoDir.'/'.$name.'_'.$index.'.log';
    if (!file_exists($listFile)) return;
    error_log("\n".date('Y-m-d H:i:s')." Synchronize $listFile\n", 3, $logFile);
    $logfh = fopen($listFile, 'r');
    fseek($logfh, $pointer);
    $list = array();
    while (!feof($logfh)) $list[] = trim(fgets($logfh));
    $pointer = ftell($logfh);
    fclose($logfh);
  
    umask(0);
    foreach ($list as $item) {
      $pos = strpos($item, $srcDir);
      if ($pos === false) continue;
      $file1 = substr($item, $pos);
      $file2 = $destDir.substr($file1, strlen($srcDir));
      if (file_exists($file1)) {
        $status = file_exists($file2)? "overwrite": "new";
        if ($ignore && $status=="overwrite" && filesize($file1)==filesize($file2)) continue;
        $path2 = substr($file2, 0, strrpos($file2, "/"));
        if (!file_exists($path2)) mkdir($path2, 0777, true);
        error_log(date('Y-m-d H:i:s')." Copy $status $file2\n", 3, $logFile);
        copy($file1, $file2);
      }
    }

    $date = substr($index, 0, 4).'-'.substr($index, 4, 2).'-'.substr($index, 6);
    $newId = date('Ymd', strtotime("$date + 1 day"));
    $nextFile = file_exists($infoDir.'/'.$name.'_'.$newId.'.log');
    if ($nextFile) {
      $index = $newId;
      $pointer = 0;
    }

    $fh = fopen($posFile, 'w');
    fputs($fh, $name."\n");
    fputs($fh, $index."\n");
    fputs($fh, $pointer."\n");
    fclose($fh);
  }
  while ($nextFile);
}
