<?php
$gapsIni = realpath(dirname(__FILE__) . "/../../GAPS.ini");
$config = parse_ini_file($gapsIni);
$gapsApacheConf = $config['PORTAL']. "/Tasks/config/GAPS.Apache.conf";

$apache = realpath($config['PHP'] . "/../httpd/conf/");

function convertGapsConf () {
	global $config;
	global $apache;
	global $gapsApacheConf;
	
	if (!$apache) return "Apache-Verzeichnis nicht gefunden.";
	if (!file_exists($apache . "/GAPS.conf")) return "GAPS.conf nicht gefunden.";

	$httpdConf = file_get_contents($apache . "/httpd.conf");
	$match = array();

	if (!preg_match('/\r\nListen (\d+)/im', $httpdConf, $match)) return "Apache-Port nicht gefunden.";

	$httpdConf = preg_replace('/\r\nListen \d+/im', "", $httpdConf);
	$port = $match[1];

	$httpdConf = str_replace('GCPS.conf', 'php5.module.conf', $httpdConf);
	$httpdConf .= "\r\n" . 'include "' . str_replace("\\", "/", $config['PORTAL']) . '/Tasks/config/GAPS.Apache.conf"';

	if (!rename($apache . "/GAPS.conf", $gapsApacheConf)) return "GAPS.conf laesst sich nicht verschieben.";

	if (!file_put_contents($apache . "/httpd.conf", $httpdConf)) {
		file_put_contents($config['PORTAL']. "/Tasks/httpd.conf", $httpdConf);
		return "httpd.conf laesst sich nicht ueberschreiben. Bitte manuell austauschen.";
	}

	unlink($apache. "/GCPS.conf");
	
	$gapsConf = file_get_contents($gapsApacheConf);
	$gapsConf = "Listen " . $port . "\r\n\r\n" . $gapsConf;
	file_put_contents($gapsApacheConf, $gapsConf);
	return "";
}

function addGapsUrl () {
	global $config;
	global $gapsIni;
	global $gapsApacheConf;

	$gapsConf = file_get_contents($gapsApacheConf);

	if (!preg_match('/\nAlias "\/(.*)" "(.*)"\r\n/im', $gapsConf, $match)) return "Alias unbekannt";
	$subdir = $match[1];

	if (preg_match('/Listen (\d+)/im', $gapsConf, $match)) {
		$port = $match[1];
	} else {
		$port = "80";
	}

	$output = array();
	exec("systeminfo", $output);
	$output = implode("\r\n", $output);

	if (!preg_match('/(LAN-Verbindung|Ethernet0|Local Area)[^[]*\[01\]:\s([\d\.]+)/im', $output, $match)) return "IP-Adresse unbekannt.";
	$host = $match[2];

	$config['GAPS_URL'] = "http://{$host}:{$port}/{$subdir}";

	file_put_contents($gapsIni, "\r\nGAPS_URL=\"{$config['GAPS_URL']}\"" , FILE_APPEND);
	return "";
}

function addRemoteTasks() {
	global $gapsApacheConf;
	
	$gapsConf = file_get_contents($gapsApacheConf);
	if (!preg_match('/\nAlias "\/Remote\/" "(.*)"\r\n/im', $gapsConf, $match)) {
		$alias = 'Alias "/Remote/" "' . str_replace("\\", "/", realpath(dirname(__FILE__)."/../Remote")) . '/"' . "\r\n\r\n";
		$gapsConf = str_replace("\r\n<Dir", $alias . "\r\n<Dir", $gapsConf);
		file_put_contents($gapsApacheConf, $gapsConf);
	}
	return "";
}


if (!file_exists($gapsApacheConf)) {
	echo convertGapsConf();
}

if (!isset($config['GAPS_URL'])) {
	echo addGapsUrl();
}

if (file_exists($gapsApacheConf)) {
	echo addRemoteTasks();
}

echo "Apache-Umstellung erfolgreich.";
