<?php

/***
* cadaver command list generator
* for webdav file syncronization
*
* Copyright 2014 Erinome.net
***/

$outfile = "/tmp/.phpsync.list";
$remotebase = "/mnt/davfs2.yandex";
$cntrops = 0;
$cntlops = 0;

file_put_contents($outfile,"open https://webdav.yandex.ru".PHP_EOL);

/* place your backup directories here */
phpsync("/srv/content","/backup/content");
phpsync("/srv/otherdir","/backup/otherdir");

function phpsync($from,$to)
{
	global $outfile, $remotebase, $cntrops, $cntlops;
	// reverse scan for deleted files in remote fs
	$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($remotebase.$to, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
	foreach ($iterator as $path)
	{
		$remotepath = $path->__toString();
		$localpath = $from.str_replace($remotebase.$to,'',$remotepath);
		// is it a directory?
		if ($path->isDir() && !is_dir($localpath))
		{
			$cntlops++;
			echo "deleting locally missing directory ".$remotepath.PHP_EOL;
			rmdir($remotepath);
		}
		// or a file?
		if ($path->isFile() && !is_file($localpath))
		{
			$cntlops++;
			echo "deleting locally missing file ".$remotepath.PHP_EOL;
			unlink($remotepath);
		}
	}
	// remote destination paths check
	$remotepath = "";
	foreach (explode(DIRECTORY_SEPARATOR,$to) as $path)
	{
		if (!strlen($path)) continue;
		$remotepath .= "/".$path;
		if (!is_dir($remotebase.$remotepath))
		{
			$cntops++;
			$command = "mkcol \"".$remotepath."\"".PHP_EOL;
			file_put_contents($outfile,$command,FILE_APPEND);
		}
	}
	// direct scan for missing or outdates files in remote fs
	$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($from, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
	foreach ($iterator as $path)
	{
		$localpath = $path->__toString();
		$remotepath = $remotebase.$to.str_replace($from,'',$localpath);
		// is it a directory?
		if ($path->isDir() && !is_dir($remotepath))
		{
			$cntrops++;
			$command = "mkcol \"".str_replace($remotebase,'',$remotepath)."\"".PHP_EOL;
			file_put_contents($outfile,$command,FILE_APPEND);
		}
		// or a file?
		if ($path->isFile())
		{
			$write = false;
			// simple case: file just isn't there
			if (!is_file($remotepath))
			{
				$write = true;
			}
			// filesize doesn't match
			elseif (filesize($localpath) <> filesize($remotepath))
			{
				$write = true;
			}
			if ($write)
			{
				$cntrops++;
				$command = "put \"".$localpath."\" \"".str_replace($remotebase,'',$remotepath)."\"".PHP_EOL;
				file_put_contents($outfile,$command,FILE_APPEND);
			}
		}
	}
}

if ($cntrops)
	file_put_contents($outfile,"exit".PHP_EOL,FILE_APPEND);
else
	file_put_contents($outfile,"");

echo "Finished! [".$cntlops."] local operations done, [".$cntrops."] remote operations pending.".PHP_EOL;

?>