<?php

$merge = false;
$thorough = false;

umask(0);
$destPath = $argv[2];
rscandir($argv[1]);

function rscandir($path) {
  $count = 0;
  foreach (scandir($path) as $dir) {
    if ($dir=='.' || $dir=='..') continue;
    $dname = $path.'/'.$dir;
    $count++;

    if (is_dir($dname)) {
      if (rscandir($dname)==0) {
        echo "remove $dname\n";
        rmdir($dname);
        $count--;
      }
    }
    else {
      $destdir = $GLOBALS['destPath']."/$path";
      $dest = "$destdir/$dir";
      if (!file_exists($dest)) {
        if ($GLOBALS['merge']) {
          echo "rename $dname\n";
          if (!file_exists($destdir)) mkdir($destdir, 0777, true);
          rename($dname, $dest);
          $count--;
        }
      } else {
        $size = filesize($dname);
        if (($size==0 || $size==filesize($dest)) && (!$GLOBALS['thorough'] || crc32(file_get_contents($dname))==crc32(file_get_contents($dest)))) {
          echo "delete $dname\n";
          unlink($dname);
          $count--;
        }
      }
    }
  }
  return $count;
}
