<?php

OnlyShowIf(CheckAdmin());

	function tailCustom($filepath, $lines = 45, $adaptive = true) {
		// Open file
		$f = @fopen($filepath, "rb");
		if ($f === false) return false;
		// Sets buffer size
		if (!$adaptive) $buffer = 4096;
		else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));
		// Jump to last character
		fseek($f, -1, SEEK_END);
		// Read it and adjust line number if necessary
		// (Otherwise the result would be wrong if file doesn't end with a blank line)
		if (fread($f, 1) != "\n") $lines -= 1;
		
		// Start reading
		$output = '';
		$chunk = '';
		// While we would like more
		while (ftell($f) > 0 && $lines >= 0) {
			// Figure out how far back we should jump
			$seek = min(ftell($f), $buffer);
			// Do the jump (backwards, relative to where we are)
			fseek($f, -$seek, SEEK_CUR);
			// Read a chunk and prepend it to our output
			$output = ($chunk = fread($f, $seek)) . $output;
			// Jump back to where we started reading
			fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
			// Decrease our line counter
			$lines -= substr_count($chunk, "\n");
		}
		// While we have too many lines
		// (Because of buffer size we might have read too many)
		while ($lines++ < 0) {
			// Find first newline and remove all text before that
			$output = substr($output, strpos($output, "\n") + 1);
		}
		// Close file and return
		fclose($f);
		return trim($output);
	}

$title = "Driver Log";

include($installfolder.'/include/tmpl.php');
include($installfolder.'/model/relationship.php');

T('header-basic','title='.$title.'|backtrace=<li><a href="'.$siteroot.'/admin">Administration</a></li>');

ST('section','class=content');
	ST('row');
		
		ST('full');
			ST('box-collapsible','title=Log Lines');?>
				<a href="<?php echo $siteroot; ?>/admin/drivers/logs" class="btn btn-success">Return to Driver list</a><?php
				SS('footer');
				ST('table');
					$base = '/var/log/ardi';
					$fn = $base;
					
					if (isset($_REQUEST['id']))
					{
						$prt = filter_var($_REQUEST['id'],FILTER_VALIDATE_INT);
						if ($prt == FALSE)
						{
							exit;
						}
						$fn .= '/driver-'.$prt.'.log';
					}
					
					if (isset($_REQUEST['src']))
					{
						$fn = $base;
						$id = filter_var($_REQUEST['src'],FILTER_VALIDATE_INT);
						if ($id == FALSE)
						{
							exit;
						}
						$fn .= '/source-'.$id.'.log';
					}
					
					if (file_exists($fn))
					{
						echo '<h3>Showing Last 45 Log Lines</h3>';
						$dta = tailCustom($fn);//file_get_contents($fn);
						echo str_replace("\n","<br/>",htmlspecialchars($dta));
					}
					else
					{
						echo '<h3>No Matching Log File Found</h3>';
						echo 'Local Log File '.$fn.' Not Found';
					}
				ET();
			ET();
		ET();
	ET();	
ET();

?>
