<?php
/*
    Copyright (C) 2017 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace GnuBoat;

require_once(__DIR__ ."/../autoloader.php");

class ServiceLogFiles extends Service
{
	function __construct()
	{
		parent::__construct();
	}

	protected function process()
	{
		$debug = $this->debug();
		$config = new Config();

		if(!array_key_exists("logfilesSelected", $_POST)){
			// return list with available log files
			$files = glob($config->logDirectory() ."*.log");
			array_walk($files, 'GnuBoat\ServiceLogFiles::stripLogDirectory');

			header('Content-Type: application/json');
			if($debug > 0){
				echo json_encode($files,  JSON_PRETTY_PRINT) ."\n";
			}
			else{
				echo json_encode($files) ."\n";
			}
		}
		else{
			// prepare a download of available log files
			$files = $_POST["logfilesSelected"];
			if(count($files) < 1){
				return;
			}
			elseif(count($files) == 1){
				$content = file_get_contents($config->logDirectory() . $files[0]);
				if($content === false){
					echo "<html><head></head><body>Failed to read logfile ". $files[0] ."</body></html>";
				}
			
				header('Content-Type: text/plain');
				header('Content-disposition: attachment; filename="'. $files[0] .'"');
				header('Content-Length: ' . filesize($config->logDirectory() . $files[0]));
				echo $content;
			}
			else{
				$date = new \DateTime('NOW');
				$archiveName = "gnuboat-logs-". $date->format("Y-m-d");
			
				// provide files as zip file
				$tmpArchive = tempnam(sys_get_temp_dir(), $archiveName);
				$zip = new \ZipArchive();
				if($zip->open($tmpArchive, \ZipArchive::CREATE) !== TRUE){
					echo "<html><head></head><body>Failed to create zip file</body></html>";
					return;
				}
				foreach($files as $file){
					if($zip->addFile($config->logDirectory() . $file, $archiveName ."/". $file) !== true){
						$zip->close();
						echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
						return;
					}
				}
				if($zip->close() !== true){
						echo "<html><head></head><body>Failed to save zip file</body></html>";
						return;
				}
				
				echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
				
				//Send zip folder
				while (ob_get_level()) {
					ob_end_clean();
				}
				ob_start();
				header('Content-Type: application/zip');
				header('Content-Transfer-Encoding: Binary');
				header('Content-disposition: attachment; filename=' . $archiveName . '.zip');
				header('Content-Length: ' . filesize($tmpArchive));
				ob_flush();
				ob_clean();
				readfile($tmpArchive);
				unlink($tmpArchive);
				return;
			}
		}
	}

	public static function stripLogDirectory(&$item, $key)
	{
		$config = new Config();
		$item = str_replace($config->logDirectory(), "", $item);
	}
}

?>
