<?PHP

    //====== custom parameters ==========================
    
    $login = "login";
    $password = "password";
    
    //=========================================
    
	require_once('Common.php');
	require_once('util\http.php');
	
	use XmlSerialization\XmlSerializer;	
    use \com\veeam\www\ent\v1_0 as restApi;
    
    
	$http = new HttpContext('127.0.0.1', 9399);
	$restApiInteraction = new RestApiInteraction($http);
	
	// log in using basic authentification
	$session = $restApiInteraction->LogInByBasicAuthentication($login, $password);
	if ($session->SessionId == null) { echo 'Login failed'; exit; }

	echo 'Logged in successfully, sessionId : ' . $session->SessionId . "\r\n";

	// get first existing job to clone
	$existingJobRef = $restApiInteraction->GetObject(
						RelativeUrls::JobRefs, 
						ClassHelper::CombineWithNamespace("EntityReferenceListType")
						)->Ref[0];
	if (!$existingJobRef) { echo 'Failed to get jobs data'; exit; }
    $existingJob =  $restApiInteraction->GetObject(
                        LinkHelper::FindLink($existingJobRef->Links->Link, LinkRelations::Alternate)->Href,
                        ClassHelper::CombineWithNamespace("JobEntityType")
                        );
                        
	// get first repository
	$repository = $restApiInteraction->GetObject(
						RelativeUrls::RepositoryRefs, 
						ClassHelper::CombineWithNamespace("EntityReferenceListType")
						)->Ref[0];
	if (!$repository){ echo 'Failed to get repositories data'; exit; }
	
	echo 'Using job "' . $existingJob->Name . "\"\r\n";
	echo 'Using repository "' . $repository->Name . "\"\r\n";
	
	// start to clone task
    $cloneJobLink = LinkHelper::FindLink($existingJob->Links->Link, LinkRelations::CloneRel);
    $jobCloneSpec = new restApi\JobCloneSpecType();
	$jobCloneSpec -> BackupJobCloneInfo = new restApi\BackupJobCloneInfoType();
	$jobCloneSpec -> BackupJobCloneInfo -> JobName = $existingJob->Name . ' cloned at ' . date('Y-m-d H:i:s');
	$jobCloneSpec -> BackupJobCloneInfo -> FolderName = 'job-cloned-' . date('Y-m-d-\a\t-H-i-s');
	$jobCloneSpec -> BackupJobCloneInfo -> RepositoryUid = $repository->UID;
    
	$cloningTask = $restApiInteraction->PostObject(
                            $cloneJobLink -> Href,
                            $jobCloneSpec,
                            ClassHelper::CombineWithNamespace("TaskType")
                            );
	if (!$cloningTask){ echo 'Failed to clone job'; exit; }
	
	// wait while it's running
	if (strcmp($cloningTask->State, 'Running') == 0) {
		$cloningTask = $restApiInteraction->WaitForTaskResult($cloningTask->Href, 1);
	}
	
	// check if clone task is succeeded
	if (!$cloningTask->Result->Success) { echo "Job cloning failed\r\n\r\n"; var_dump($cloningTask); exit; }
	
	echo "Job cloned successfully. Removing tasks\n";
    $restApiInteraction->DeleteTask($cloningTask);
    echo "Logout";
    $restApiInteraction->Logout($session);
?>