<?php

class CopyController
{
	public static function Run ($argv)
	{
		if (count($argv) < 3) die();
		$copyCtrl = new CopyController();
		$tol = (count($argv) > 3) ? $argv[3] : 20;
		$copyCtrl->Copy($argv[1], $argv[2], $tol);
	}

	public function Copy ($source, $target, $tolerance = 20, $timeout = 300, $retry = 20)
	{
		if (!is_dir($source)) {
			$source = dirname($source);
		}
		$dir = dir($source);
		$start = strtotime("now");
		$oldest = $start - ($tolerance * 60 * 60);

		for ($i = 0; $i < $retry; $i++) {
			if ($this->anyFileYoungerThan($source, $oldest) && $this->AllFilesOlderThan($source, strtotime("-10 min"))) {
				$mins = floor((strtotime("now") - $start) / 60);
				if ($mins > 1) {
					echo "* Wartezeit: {$mins} Min.\r\n";
				}
				break;
			}
			if ($i == 0) {
				if (!$this->anyFileYoungerThan($source, $oldest)) {
					echo "  Es liegen noch keine aktuellen Daten vor\r\n";
				} else {
					echo "  Der Export ist noch nicht vollstaendig\r\n";
				}
			}
			echo "  Warte 5 Minuten...\r\n";
			sleep($timeout);
		}
		if (!$this->anyFileYoungerThan($source, $oldest)) {
			echo "(CR0004) Alle Dateien sind veraltet. Prozess wurde abgebrochen.\r\n";
			exit(5);
		}

		while ($txtFile = $dir->read()) {
			if (!preg_match('/\.txt$/i', $txtFile)) {
				continue;
			}
			$sourceFile = $source . "\\" . $txtFile;
			$targetFile = $target . "\\" . $txtFile;

			$modified = date("d.m.Y H:i", filemtime($sourceFile));

			if (filemtime($sourceFile) >= $oldest) {
				$unlocker = exec("cmd.exe /c unlocker.bat {$targetFile}");
				if (copy($sourceFile, $targetFile)) {
					echo "  {$txtFile} ({$modified})\r\n";
					$this->Replace($targetFile);
				} else {
					echo $unlocker . "\r\n";
					echo "(CR0002) Kopieren von '{$sourceFile}' fehlgeschlagen.\r\n";
				}
			} else {
				echo "(CR0005) Datei '{$sourceFile}' ist nicht aktuell. Stand: {$modified}\r\n";
			}
		}
	}

	public function AllFilesOlderThan ($dirname, $timestamp)
	{
		$dir = dir($dirname);
		while ($txtFile = $dir->read()) {
			if (!preg_match('/\.txt$/i', $txtFile)) {
				continue;
			}
			if (filemtime($dirname . "\\" . $txtFile) > $timestamp) {
				return false;
			}
		}
		return true;
	}

	public function AnyFileYoungerThan ($dirname, $timestamp)
	{
		$dir = dir($dirname);
		while ($txtFile = $dir->read()) {
			if (!preg_match('/\.txt$/i', $txtFile)) {
				continue;
			}
			if (filemtime($dirname . "\\" . $txtFile) > $timestamp) {
				return true;
			}
		}
		return false;
	}

	public function Replace ($filename)
	{
		if (!isset($filename) || !file_exists($filename)) {
			return "(CR0003) Die Datei '{$filename}' ist nicht vorhanden.\r\n";
		}
		$tempfile = $filename . ".temp";

		@unlink($tempfile);
		if (!rename($filename, $tempfile)) return "(CR0007) Die Datei '{$filename}' ist schreibgeschuetzt.\r\n";
		$readHandle = fopen($tempfile, "r");
		$writeHandle = fopen($filename, "w+");
		
		if (!$readHandle) return "(CR0008) Die temporaere Datei '{$tempfile}' ist nicht vorhanden.\r\n";
		if (!$writeHandle) return "(CR0009) Die Datei '{$filename}' ist schreibgeschuetzt.\r\n";
		
		while (!feof($readHandle)) {
			fwrite($writeHandle, str_replace('"', "'", fgets($readHandle)));
		}
		fclose($readHandle);
		fclose($writeHandle);
		unlink($tempfile);
		return true;
	}
}