<?php

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$accessControl = array(
    "ProfileRequired" => true,
    "StreamFile" => true
);
include_once '../../AccessControl.php';

// if ($validUserRequired && !$session->canUpdateLogs()) {
// 	//echo $template->NoAccess();
// 	exit();
// }

if(!isset($profile)) {
	$profile = new SiteProfile($conf);
}

$updateProgressLogLoc = $profile->datamanagerDir.$profile->profilename."/{$profile->profilename}_update_progress.lwa.log"; 

if (isset($_REQUEST['startpos'])) {
    $startpos = $_REQUEST['startpos'];
} else {
    $startpos = 0;
}

if ($startpos == 0) {
    sleep(1);
}

clearstatcache();
$currentSize = filesize($updateProgressLogLoc);

$content = "";
$clear = false;
$finished = false;

if ($startpos > $currentSize) {
    $clear = true;
    $startpos = 0;
}

while ($finished==false) {
    clearstatcache();
    $currentSize = filesize($updateProgressLogLoc);
    
    if ($startpos < $currentSize) {        
        
        $fh = fopen($updateProgressLogLoc, "r");
        fseek($fh, (int)$startpos);
        $i=0;
        $output = array();
        while ($d = fgets($fh)) {
            //$content.=$d."<br />";

            if (strpos($d, "Finished]")!==false) {
                //fclose($fh);
                $finished = true;
                //exit();
            }
            $output[] = $d;          
            
        }
        fclose($fh);
        $n = count($output);
        if ($n > 100) {
            // to much to send in one go, just output the last one
            Stream($output[0]);
            Stream("Progress Stream is too fast, skipping 95 lines of output ...");
            $n = $n - 5;
            Stream($output[$n]); 
            Stream($output[$n++]); 
            Stream($output[$n++]); 
            Stream($output[$n++]); 
            Stream($output[$n++]); 
        } else {
            foreach($output as $d) {
                Stream($d);
            }
        }
        
        //Stream($d);
        $startpos = $currentSize;
        //$res = array("Status" => "Success", "contents" => $content, "startpos" => $currentSize, "finished" => $finished, "clear_screen" => $clear);
        //echo json_encode($res);        
    } else {
        sleep(2);
    }
}

// } else {
//     sleep(5);
//     //echo '{"Status": "Warning", "Message": "'. _NO_NEW_CONTENT_TO_SEND .'", "startpos": '.$startpos.', "finished": false , "clear_screen": "false" }';
//     Stream(_NO_NEW_CONTENT_TO_SEND);
// }
?>