#!/usr/bin/php
<?php
if(!isset($argv[1])){
	echo "usage: emergesync [svn-revision] [downgrade_allowed]\r\n";
	echo "\tOR emergesync target\r\n";
	exit;
}
if($argv[1]=="target"){
    $exec=shell_exec("update_getmytargetrev");
    $exec=explode("\n",$exec);
    echo "Calling update_getmytargetrev...\r\n";
    $infodata=array();
    foreach($exec as $line){
	$line=trim($line);
	echo "\r".$line."\r\n";
	$exp = explode(": ",$line);
	if(count($exp)==2){
	    $infodata[$exp[0]]=$exp[1];
	}
    }
    if($infodata["Target Revision is"]<1){
	echo "Invalid Target Revision :(\r\n";
	exit(1);
    }
    if(strlen($infodata["Target Revision is from"])!=43 && strlen($infodata["Target Revision is from"])!=44){
	echo "Invalid Target Revision date (".strlen($infodata["Target Revision is from"]).") :(\r\n";
	exit(1);
    }
    $rev=$infodata["Target Revision is"];
}
else{
    $rev = $argv[1];
}
$revint = (int)$rev;

$currev=-1;
$repos = scandir("/var/db/repos");
foreach($repos as $repo){
	if($repo=="." || $repo=="..") continue;
	if(is_dir("/var/db/repos/".$repo."/.svn")){
		$exec = shell_exec("svn info /var/db/repos/".$repo);
		$exec=explode("\n",$exec);
		foreach($exec as $line){
		    if(substr($line,0,10)=="Revision: "){
			$thisrev=trim(substr($line,10));
			if($currev==$thisrev){
			    // all ok
			}
			elseif($currev==-1){
			    $currev=$thisrev;
			}
			else{
			    echo "Repos have different revs? (".$currev."/".$thisrev.") :( use highest rev...\r\n";
			    if($currev<$thisrev){
				$currev=$thisrev;
			    }
			}
		    }
		}
	}
}


if($rev!=$revint){
	echo "usage(2): emergesync [svn-revision]\r\n";
	exit(1);
}

if($currev>$revint){
    $downgradeallowed=false;
    if(isset($argv[2]) && $argv[2]=="downgrade_allowed"){
        $downgradeallowed=true;
    }
    if(!$downgradeallowed){
        echo "Downgrade from ".$currev." to ".$revint." not possible :(\r\n";
        exit(1);
    }
}


$repos = scandir("/var/db/repos");
foreach($repos as $repo){
	if($repo=="." || $repo=="..") continue;
	if(is_dir("/var/db/repos/".$repo."/.svn")){
		echo "sync repo ".$repo." to revision ".$revint."...\r\n";
		passthru("svn update -r ".$revint." /var/db/repos/".$repo);
	}
}
