<?php

	const RSCANDIR_INCLUDE_FILES = 1;
	const RSCANDIR_INCLUDE_DIRECTORIES = 2;
	const RSCANDIR_INCLUDE_ALL = 3;

	function rscandir($dir, $flags = RSCANDIR_INCLUDE_ALL)
	{
		if (!is_dir($dir))
		{
			return false;
		}

		$result = array();
		$items = scandir($dir);
		foreach ($items as $item)
		{
			if ($item == "." || $item == "..") continue;

			if (($flags & RSCANDIR_INCLUDE_FILES) == RSCANDIR_INCLUDE_FILES && !is_dir($dir . "/" . $item))
			{
				$result[] = $dir . "/" . $item;
			}
			if (is_dir($dir . "/" . $item))
			{
				if (($flags & RSCANDIR_INCLUDE_DIRECTORIES) == RSCANDIR_INCLUDE_DIRECTORIES)
				{
					$result[] = $dir . "/" . $item;
				}

				$items2 = rscandir($dir . "/" . $item, $flags);
				if ($items2 !== false)
				{
					$result = array_merge($result, $items2);
				}
			}
		}
		return $result;
	}

	$argv = $_SERVER["argv"];

	// install_mysql.php databasename username password

	if (count($argv) > 1)
	{
		// usage: mocha oms install
		// php install_mysql.php DatabaseName UserName Password PortNumber
		$DatabaseName = $argv[1];

		$HostName = "127.0.0.1";
		$PortNumber = 3306;

		if (count($argv) >= 4)
		{
			$UserName = $argv[2];
			$Password = $argv[3];
			if (count($argv) >= 5)
			{
				$PortNumber = $argv[4];
			}
		}
		else
		{
			echo( "enter database credentials\n\nuser name: ");
			$UserName = trim(fgets(STDIN));
			if ($UserName === false)
			{
				return;
			}
	
			system("stty -echo");
	
			echo("password: ");
			$Password = trim(fgets(STDIN));
			if ($Password === false)
			{
				return;
			}
			
			system("stty echo");
		}

		echo("\n\n");
		echo("installing mocha on `" . $DatabaseName . "` with user `" . $UserName . "` and password\n");

		$pdo = new \PDO("mysql:host=" . $HostName . ";port=" . $PortNumber . ";dbname=" . $DatabaseName, $UserName, $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);
		}

		/*
		echo ("enter new name for super tenant? [super]: ");
		$TenantName = trim(fgets(STDIN));
		if ($TenantName === false)
		{
			return;
		}
		if ($TenantName == "")
		{
			$TenantName = "super";
		}

		print ("tenant name: '" . $TenantName . "'\n");
		*/
		
		$TenantName = "super";
		// 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)));

	}
	else
	{
		echo("usage: install_mysql.php DatabaseName [UserName] [Password]\n");
	}

?>