<?php
	require_once ("lib/phast/System.inc.php");

	use Phast\System;

	function get_system_user_name()
	{
		ob_start();
		system("whoami");
		$username = ob_get_contents();
		ob_end_clean();
		return $username;
	}

	function write_value($file, $value)
	{
		if (is_array($value))
		{
			fwrite($file, "[ ");
			$i = 0;
			$ct = count($value);
			foreach ($value as $val)
			{
				write_value($file, $val);
				if ($i < $ct - 1)
				{
					fwrite($file, ", ");
				}
				$i++;
			}
			fwrite($file, " ]");
		}
		else if (is_string($value))
		{
			fwrite($file, "\"" . $value . "\"");
		}
		else
		{
			fwrite($file, $value);
		}
	}


	$username = get_system_user_name();
	$datadir = "data";
	if (!file_exists(dirname(__FILE__) . "/" . $datadir))
	{
		$datadir = null;
	}

	if ($_SERVER["REQUEST_METHOD"] == "POST")
	{
		$err = 0;

		$file = fopen(dirname(__FILE__) . "/include/Configuration.inc.php", "w");
		
		if (!$file)
		{
			$err = 1;
			// "could not create configuration file - please grant access to " . system("whoami"));
		}
		else
		{
			// write config file
			fwrite($file, "<?php\n");
			fwrite($file, "use Phast\IncludeFile;\nuse Phast\System;\n");
			fwrite($file, "System::\$IncludeFiles[] = new IncludeFile(\"/lib/mocha/system.inc.php\", true);\n");
			fwrite($file, "System::\$EnableTenantedHosting = false;\n");

			$conf = array();
			$conf["Application.Title"] = "Mocha SUV";
			$conf["Application.DefaultTenant"] = "super";
			$conf["Application.ThemeName"] = "avondale";

			$conf["Database.ServerName"] = "localhost";
			$conf["Database.PortNumber"] = 3306;
			$conf["Database.DatabaseName"] = $_POST["Database_DatabaseName"];
			$conf["Database.UserName"] = $_POST["Database_UserName"];
			$conf["Database.Password"] = $_POST["Database_Password"];

			$conf["LoginPageRedirectURL"] = "~/madi/authgwy/$(CurrentTenantName)/login.htmld";
			$conf["Runtime.DisableAutomaticExtensionParsing"] = true;
			$conf["Paths.MasterPages"] = ["/ui/masterPages"];
			$conf["Paths.Pages"] = ["/ui/pages"];

			foreach ($conf as $key => $value) {
				fwrite($file, "System::\$Configuration[\"" . $key . "\"] = ");
				write_value($file, $value);
				fwrite($file, ";\n");
			}

			fwrite($file, "require_once (\"BeforeLaunchEvent.inc.php\");\n");
			fwrite($file, "?>");

			fflush($file);
			fclose($file);

			require_once ("lib/phast/rscandir.inc.php");

			// reset db
			$pdo = new \PDO("mysql:host=" . $conf["Database.ServerName"] . ";port=" . $conf["Database.PortNumber"] . ";dbname=" . $conf["Database.DatabaseName"], $conf["Database.UserName"], $conf["Database.Password"]);
			
			// import all the sql files
			$sql_files = rscandir("../mysql", RSCANDIR_INCLUDE_FILES);
			foreach ($sql_files as $sql_file)
			{
				echo("executing `" . $sql_file . "`\n");
				$sql = file_get_contents($sql_file);
				$pdo->exec($sql);
			}

			$TenantName = $conf["Application.DefaultTenant"];
			// generate new UUID for default tenant
			$query = "UPDATE mocha_tenants SET global_identifier = mocha_uuid_v4(), tenant_name = :tenant_name WHERE global_identifier = '2552F66B0DBE41EB8A8076DE8575A468'";
			$stmt = $pdo->prepare($query);
			$stmt->execute(array("tenant_name" => trim($TenantName)));
		}
		?>
		<!DOCTYPE html>
		<html xmlns="http://www.w3.org/1999/xhtml">
			<head>
				<title>Mocha Setup</title>
				<link rel="stylesheet" type="text/css" href="<?php echo(System::ExpandRelativePath("~/themes/avondale/theme.css")); ?>" />
			</head>
			<body>
				<form method="GET" action="<?php echo(System::ExpandRelativePath("~/")); ?>">
					<div class="uwt-page">
						<div class="uwt-header">
							<h1>Mocha Setup</h1>
							<?php
							if ($err == 1)
							{
								?>
								<p style="color: #ff0000;">Could not create configuration file - please grant access to <?php echo ($username); ?></p>
								<?php
							}
							else
							{
								?>
								<p>Your system has been configured. You can now log in to the tenant with the user name and password you specified</p>
								<?php
							}
							?>
						</div>
						<div class="uwt-content">
							<input type="submit" style="margin-left: auto; margin-right: auto; width: 200px; height: 48px; display: block;" value="Continue" />
		<?php

		echo ("<h1>Postback!</h1>");
		print_r($_POST);

		echo ("file name: " . __FILE__);

		$result = unlink(__FILE__);
		if ($result)
		{

		}
		else
		{
			echo ("<div class=\"uwt-alert uwt-visible uwt-color-danger\">Unable to remove setup.php - you might want to remove it manually</div>");
		}
						?>
						</div>
					</div>
				</form>
			</body>
		</html>
						<?php
	}
	else
	{
		$err = 0;
		$file = fopen(dirname(__FILE__) . "/include/Configuration.inc.php", "a");
		if (!$file)
		{
			$err = 1;
		}
		else
		{
			fclose($file);
		}

		?>
		<!DOCTYPE html>
		<html xmlns="http://www.w3.org/1999/xhtml">
			<head>
				<title>Mocha Setup</title>
				<link rel="stylesheet" type="text/css" href="<?php echo(System::ExpandRelativePath("~/themes/avondale/theme.css")); ?>" />
				<meta name="viewport" content="width=device-width, initial-scale=1.0" />
				<script type="text/javascript" src="<?php echo(System::ExpandRelativePath("~/scripts/phast/System.js.php")); ?>"></script>
				<script type="text/javascript" src="<?php echo(System::ExpandRelativePath("~/scripts/setup.js")); ?>"></script>
			</head>
			<body class="uwt-hide-sidebar">
				<form method="POST">
					<div class="uwt-header uwt-color-inverse">
						<img style="display: block; width: 48px; height: 48px; margin-left: auto; margin-right: auto; margin-top: 8px;" src="<?php echo(System::ExpandRelativePath("~/images/logo.svg")); ?>" />
					</div>
					<div class="uwt-page">
						<div class="uwt-header">
							<h1>Mocha Setup</h1>
							<p>Please fill out the information below to complete the initial configuration of your Mocha application server</p>
							<?php
							if ($err == 1)
							{
								?>
								<p style="color: #ff0000;">User <?php echo($username); ?> does not have access to include/Configuration.inc.php ; please grant this user permission and then <a href="<?php echo(System::ExpandRelativePath("~/setup")); ?>">retry</a></a></p></p>
								<?php
							}
							if ($datadir == null)
							{
								?>
								<p style="color: #ff0000;">Could not find the 'data' folder at the same level of setup.php; please <a id="dataDirMsgHelper" href="#">put it there</a></p>
								<?php
							}
							?>
						</div>
						<div class="uwt-content">
							<table class="uwt-formview">
								<tr class="uwt-formview-item">
									<td class="uwt-formview-item-title">
										<label for="Database_DatabaseName">Database name</label>
									</td>
									<td class="uwt-formview-item-content"><input type="text" id="Database_DatabaseName" name="Database_DatabaseName" /></td>
								</tr>
								<tr class="uwt-formview-item">
									<td class="uwt-formview-item-title">
										<label for="Database_UserName">User name</label>
									</td>
									<td class="uwt-formview-item-content"><input type="text" id="Database_UserName" name="Database_UserName" /></td>
								</tr>
								<tr class="uwt-formview-item">
									<td class="uwt-formview-item-title">
										<label for="Database_Password">Password</label>
									</td>
									<td class="uwt-formview-item-content"><input type="password" id="Database_Password" name="Database_Password" /></td>
								</tr>
							</table>
						</div>
						<div class="uwt-footer" style="text-align: right;"><input type="submit" value="Save Changes" <?php if ($datadir == null) echo (" disabled=\"disabled\""); ?> /></div>
					</div>
				</form>
			</body>
		</html>
		<?php
	}
?>