<?php

class UpdateController
{
	public static function Run ($argv)
	{
		if (!class_exists("ZipArchive")) {
			exit(25);
		}
		$beta = (count($argv) > 1);
		$updateCtrl = new UpdateController($beta);
		$version = $updateCtrl->newVersionAvailable();
		if ($version) {
			echo "Neue Version gefunden: " . $version . "\r\nUpdate ";
			echo ($updateCtrl->upgrade()) ? "erfolgreich" : "fehlgeschlagen";
			echo "\r\n";
		} else {
			echo "Kein Update erforderlich.\r\n";
		}
		$updateCtrl->pcvisit();
		$updateCtrl->symlink();		
	}

	private $url = "http://dev.global-cube.de/";
	private $path;

	public function __construct($beta = false) 
	{
		$this->path = ($beta) ? "tasks-beta/" : "tasks/";
	}
	
	public function upgrade()
	{
		$remoteZipFile = $this->url . $this->path . "scripts.zip";
		$scriptsDir = realpath(".");
		$localZipFile = $scriptsDir . "/scripts.zip";


		$zipFile = file_get_contents($remoteZipFile);
		if (!$zipFile || !class_exists("ZipArchive")) {
			return false;
		}

		file_put_contents($localZipFile, $zipFile);
		$zip = new ZipArchive();
		if (!$zip->open($localZipFile)) {
			return false;
		}

		exec("del /Q /S \"{$scriptsDir}\" ");

		$zip->extractTo($scriptsDir);
		$zip->close();
		unlink($localZipFile);
		return true;
	}

	public function newVersionAvailable ()
	{
		$serverVersion = @file_get_contents($this->url . $this->path . "version.txt");
		if (!$serverVersion) {
			return false;
		}

		$localVersionFile = "version.txt";
		if (file_exists($localVersionFile)) {
			if (file_get_contents($localVersionFile) >= $serverVersion) {
				return false;
			}
		}
		return $serverVersion;
	}

	private function pcvisit ()
	{
		require_once(dirname(__FILE__) . '/../pcvisit.php');
	}
	
	private function symlink ()
	{
		$config = parse_ini_file(dirname(__FILE__) . "/../../../GAPS.ini");

		$filename = "%USERPROFILE%\\Desktop\\GAPS Tasks " . $config['KUNDE'] . ".lnk";

		// if (file_exists($filename)) return;

		if (!isset($config['GAPS_URL'])) {
			require_once(dirname(__FILE__) . '/../apache.php');
		}
		$split = explode("/", $config['GAPS_URL']);
		$remote = "http://" . $split[2] . "/Remote/";

		file_put_contents(dirname(__FILE__) . "/../link.bat",
			'start /MIN explorer.exe /e, "' . $config['PORTAL'] . '\Tasks"' . "\r\n" .
			'start /MIN iexplore.exe -nosessionmerging "' . $config['GAPS_URL'] . 'index.php5?&rc=MISModel&rm=getModel"' . "\r\n" .
			'start /MIN iexplore.exe -nosessionmerging "' . $remote . '"' . "\r\n" .
			'start %WINDIR%\system32\cmd.exe /T:1f /K "' . $config['PORTAL'] . '\Tasks\scripts\config.bat"' . "\r\n");

		$shell = new COM('WScript.Shell');
		$shortcut = $shell->CreateShortcut(dirname(__FILE__) . "/../link.lnk");
		$shortcut->TargetPath = $config['PORTAL'] . '\Tasks\scripts\Tools\link.bat';
		$shortcut->IconLocation = "%WINDIR%\\system32\\shell32.dll, 165";
		$shortcut->Save();

		exec('copy /Y "Tools\link.lnk" "' . $filename . '"');
	}

}