<?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 existing jobs
	echo "Getting jobs data\n";
	$allJobs = $restApiInteraction->GetObject(
					RelativeUrls::JobRefs, 
					ClassHelper::CombineWithNamespace("EntityReferenceListType")
					);
	if (!$allJobs){ echo 'Failed to get jobs'; exit; }
	
	//Looking for a stopped job
	$jobFound = false;
	$startJob = null;
	foreach($allJobs->Ref as $job) {
		$tmpLastJobSession = queryLastJobSession($job->UID, $restApiInteraction);
		//if job was never started or already stopped
		if ((!isset($tmpLastJobSession)) || (isset($tmpLastJobSession) && ($tmpLastJobSession->State == "Stopped")))
		{
            $jobEntityLink = LinkHelper::FindLink($job->Links->Link, LinkRelations::Alternate);
			$startJob = $restApiInteraction->GetObject(
					$jobEntityLink->Href, 
					ClassHelper::CombineWithNamespace("JobEntityType")
					);
			$jobFound = true;
			break;
		}
	}
    
	if (!$jobFound) { echo "Cannot find stopped jobs"; exit; }
	$startJobSpec = new restApi\JobManagementSpecType();
	//network credentials to connect to remote VB service
	//$startJobSpec->Credentials = new restApi\PlainCredentialsType();
	//$startJobSpec->Credentials->UserName="user_name";
	//$startJobSpec->Credentials->Password="password12345";
	$startJobSpec->Force = true;
	echo "Starting job \"" . $startJob->Name . "\"\r\n";
    
    $linkToStart = LinkHelper::FindLink($startJob->Links->Link, LinkRelations::Start);
	$taskInfo = $restApiInteraction->PostObject(
                            $linkToStart->Href, 
                            $startJobSpec,
                            ClassHelper::CombineWithNamespace("TaskType")
                            );
	if (!$taskInfo){ echo "Failed to start job \"" . $startJob->Name . "\" starting"; exit;}
	
	if (strcmp($taskInfo->State, 'Running') == 0) {
		echo "Waiting for the job to start\r\n";
		$taskInfo = $restApiInteraction->WaitForTaskResult($taskInfo->Href, 1);
	}
    
	if (!$taskInfo->Result->Success) 
	{ 
		echo "Job failed to start\r\n"; 
		echo "Message: " . $taskInfo->Result->Message;
		var_dump($taskInfo);
        exit;
	}
	
	echo "Job started succesfully\r\n";
	echo "Waiting for the job to finish\n";
	$jobSession = queryLastJobSession($startJob->UID, $restApiInteraction);
    while (strcmp($jobSession->State, 'Working') == 0)
    {
        sleep(2);
		$jobSession = queryLastJobSession($startJob->UID, $restApiInteraction);
	}
    echo "Job finished. Last session dump\n";
    var_dump($jobSession);
    
    echo "Removing tasks\n";
    $restApiInteraction->DeleteTask($taskInfo);
    echo "Logout";
    $restApiInteraction->Logout($session);
    
    
function queryLastJobSession($jobUid, $helper) {
    $jsQuery = $helper->GetObject(
                    "/api/query?type=BackupJobSession&format=Entities&sortDesc=CreationTime&pageSize=1&page=1&filter=JobUid==" . urlencode($jobUid),
					ClassHelper::CombineWithNamespace("QueryResultType")
					);
                    
    if (!isset($jsQuery) || !isset($jsQuery->Entities) || !isset($jsQuery->Entities->BackupJobSessions)) { echo "Error occurred while retrieving last backup job session. JobUid '" . $jobUid . "'";exit; }
    
    if (isset($jsQuery->Entities->BackupJobSessions->BackupJobSession) && count($jsQuery->Entities->BackupJobSessions->BackupJobSession) > 0)
        return $jsQuery->Entities->BackupJobSessions->BackupJobSession[0];
}
	
?>