#/usr/bin/php
<?

define('PARENTSTART', time());

foreach (file('/etc/psa/psa.conf') as $line) {
	if (preg_match('/^QMAIL_MAILNAMES_D.*(\/.*)$/U', chop($line), $matches)) $mailnames = $matches[1];
	if (preg_match('/^HTTPD_VHOSTS_D.*(\/.*)$/U', chop($line), $matches)) $vhosts = $matches[1];
}

if (!(is_dir($mailnames) and is_dir($vhosts))) die("Unable to determine MAILNAMES and VHOSTS directories from the psa.conf.\n");

print "Running find against $mailnames and $vhosts directories...\n";
exec("/usr/bin/find $mailnames $vhosts -maxdepth 2 -mindepth 2", $dirlist);

foreach ($dirlist as $key => $subdir) {
	if (!pcntl_fork()) {
		$starttime = time();

		$cmd = "/usr/bin/rsync -rp --delete $subdir" . (is_dir($subdir) ? '/ ' : ' ') . '/mnt/emc' . $subdir . (is_dir($subdir) ? '/' : '');
		print getmypid() . " START $subdir $cmd\n";
		exec($cmd);
		print getmypid() . " FINISH $subdir " . (time() - $starttime) . "s\n";
		exit;
	}
	++$children;
	print "$children CHILDREN, RUNNING FOR " . gmdate('H:i:s', time() - PARENTSTART) . ", ". round(($key + 1) / count($dirlist) * 100, 2) . "% LAUNCHED\n";

	while ($children >= (file_exists('/tmp/maxchildren') ? chop(file_get_contents('/tmp/maxchildren')) : 10)) {
		pcntl_wait($status);
		--$children;
	}
}

print getmypid() . " COMPLETE... Waiting for children to finish.\n";
while (--$children) if (pcntl_wait($status) == -1) exit;

?>
