﻿<?PHP

    //====== custom parameters ==========================
    
    $backupName = "backupName";
    $filePath = "filePath";
    $savePath = "savePath";
    $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";
    
    echo "Getting backup \"$backupName\" info\n";
    $queryResult = $restApiInteraction -> GetObject(
                    "/api/query?type=Backup&format=Entities&filter=Name==\"" . urlencode($backupName) . "\"",
                    ClassHelper::CombineWithNamespace("QueryResultType")
                    );
    if (!isset($queryResult) || !isset($queryResult->Entities) 
        || !isset($queryResult->Entities->Backups) || !isset($queryResult->Entities->Backups->Backup)) { echo "Cannot find backup with the following name: '" . $backupName . "'";exit; }
        
    $backup = $queryResult -> Entities -> Backups -> Backup[0];
    
    echo "Getting restore points data for the backup\r\n";
    $restorePointsLink = LinkHelper::FindLink($backup->Links->Link, LinkRelations::Down);
    $restorePoints = $restApiInteraction -> GetObject(
                    $restorePointsLink->Href . "?format=Entity",
                    ClassHelper::CombineWithNamespace("RestorePointEntityListType")
                    );
    if (!isset($restorePoints)) { echo "Unable to retrieve restore points for backup \"" . $backupName . "\""; exit; }
    if (count($restorePoints->RestorePoint) == 0) { echo "No restore points exist for backup " . $backupName; exit;}
    
    
    foreach($restorePoints->RestorePoint as $restorePoint)
        if (!isset($latestRp) || $restorePoint->BackupDateUTC > $latestRp->BackupDateUTC)
            $latestRp = $restorePoint;
    
    echo "Getting VMs from the latest restore point\r\n";
    $vmRestorePointsLink = LinkHelper::FindLink($latestRp->Links->Link, LinkRelations::Down);
    $vmRestorePoints = $restApiInteraction -> GetObject(
                    $vmRestorePointsLink->Href . "?format=Entity",
                    ClassHelper::CombineWithNamespace("VmRestorePointEntityListType")
                    );
    if (!isset($vmRestorePoints)) { echo "Unable to retrieve VM restore points for backup \"" . $backupName . "\""; exit;}
    if (count($vmRestorePoints->VmRestorePoint) == 0) { echo "No VM restore points exist in backup \"" . $backupName . "\""; exit;}
    
    $vmRestorePoint = $vmRestorePoints->VmRestorePoint[0];
    
    echo "Mounting the VM restore point\r\n";
    $mountLink = LinkHelper::FindLink($vmRestorePoint->Links->Link, LinkRelations::Create);
    $mountTask = $restApiInteraction->PostObject(
                                    $mountLink->Href, 
                                    null,
                                    ClassHelper::CombineWithNamespace("TaskType")
                                    );
                                    
    echo "Waiting for the mount task result\r\n";
    if (strcmp($mountTask->State, 'Running') == 0) {
		$mountTask = $restApiInteraction->WaitForTaskResult($mountTask->Href, 1);
	}
    
    // check if clone task is succeeded
	if (!$mountTask->Result->Success) { echo "Mounting restore point failed\r\n\r\n"; var_dump($mountTask); exit; }
    
    echo "VM restore point mounted successfully. Looking for root entry info\n";
    $relatedLink = LinkHelper::FindLink($mountTask->Links->Link, LinkRelations::Related);
    $vmMountPoint = $restApiInteraction -> GetObject(
                    $relatedLink->Href,
                    ClassHelper::CombineWithNamespace("VmRestorePointMountType")
                    );
                    
    $pathParts = explode("/", $filePath);
    foreach($vmMountPoint->FSRoots->DirectoryEntry as $de)
    {
        if ($de->Name == $pathParts[0])
        {
            $drive = $de;
            break;
        }
    }
    
    if (!$drive) { echo "Drive " . $pathParts[0] . " was not found\n"; var_dump($vmMountPoint); exit; }
    
    echo "Drive entry \"" . $pathParts[0] . "\" found\n";
    $driveEntry  = $restApiInteraction -> GetObject(
                    $drive->Href,
                    ClassHelper::CombineWithNamespace("FileSystemEntryType")
                    );
    $driveEntry = $driveEntry->DirectoryEntry;
    $downLink = FindListAllLink($driveEntry->Links->Link);
    
    $allItems  = $restApiInteraction->GetObject(
                        $downLink->Href,
                        ClassHelper::CombineWithNamespace("FileSystemEntriesType")
                    );
    
    for($i = 1; $i < count($pathParts); $i++)
    {   
        $currItem = null;
        
        echo "Looking for the file \"" . $pathParts[$i] . "\"\n";
        $fsItems = $i < count($pathParts) - 1 ? $allItems->Directories->DirectoryEntry : $allItems->Files->FileEntry;
        foreach($fsItems as $fsItem)
        {
            if ($fsItem->Name == $pathParts[$i])
            {
                $currItem = $fsItem;
                break;
            }
        }
        
        if ($currItem == null) { echo "File not found"; exit; }
        
        if ($i < count($pathParts) - 1)
        {
            $downLink = FindListAllLink($currItem->Links->Link);
            $allItems  = $restApiInteraction -> GetObject(
                            $downLink->Href,
                            ClassHelper::CombineWithNamespace("FileSystemEntriesType")
                        );
        }
        else
        {
            $restoreFileLink = LinkHelper::FindLink($currItem->Links->Link, LinkRelations::Restore);
        }
    }
    
    echo "Starting to restore file\n";
    $restoreFileTask = $restApiInteraction -> PostObject(
                            $restoreFileLink->Href,
                            null,
                            ClassHelper::CombineWithNamespace("TaskType")
                        );    
    echo "Waiting for the restoration task result\r\n";
    if (strcmp($restoreFileTask->State, 'Running') == 0) {
		$restoreFileTask = $restApiInteraction->WaitForTaskResult($restoreFileTask->Href, 1);
	}
    // check if clone task is succeeded
	if (!$restoreFileTask->Result->Success) { echo "Restoration failed\r\n\r\n"; var_dump($restoreFileTask); exit; }
    
    echo "File was restored successfully. Start downloading\n";
    
    $downloadLink = LinkHelper::FindLink($restoreFileTask->Links->Link, LinkRelations::Download);
    $content = file_get_contents($downloadLink->Href);
    file_put_contents($savePath, $content);
    
    echo "File downloaded. Removing tasks\n";
    $restApiInteraction->DeleteTask($mountTask);
    $restApiInteraction->DeleteTask($restoreFileTask);
    echo "Logout";
    $restApiInteraction->Logout($session);
    
    
    
    
    
function FindListAllLink($links)
{    
    $downLinks = LinkHelper::FindLinks($links, LinkRelations::Down);
    foreach($downLinks as $downLink)
    {
        if (substr($downLink->Href, -strlen("listAll") == "listAll"))
            break;
    }
    
    return $downLink;
}