<?php

/*
 * Copyright (C) 2002-2021 AfterLogic Corp. (www.afterlogic.com)
 * Distributed under the terms of the license described in LICENSE
 *
 */

$COMMAND = isset($argv[1]) ? $argv[1] : '';

// Dispatch table
$dispatchTable = array( 
	'configure_pro' => 'configure_pro',
	'configure_lite' => 'configure_lite',
	'check_version' => 'check_version'
) ;

// Generate arguments
$dispatching_args = $argv;
unset($dispatching_args[0]);
unset($dispatching_args[1]);

$dispatching_args = array_values($dispatching_args);

// Dispatching 
$entryPoint = NULL;
if (isset($dispatchTable[$COMMAND]))
{
	$entryPoint = $dispatchTable[$COMMAND];
}

exit($entryPoint ? $entryPoint($dispatching_args) : 1);

function configure_webmail($args, $bPro = false)
{
	$bInstall = isset($args[1]);
	
	$WEBMAIL_ROOT = isset($args[0]) ? $args[0] : '';
	include_once realpath($WEBMAIL_ROOT).'/system/autoload.php';
	\Aurora\System\Api::Init(true);
	\Aurora\System\Api::GetModuleManager()->SyncModulesConfigs();

	$oSettings = \Aurora\System\Api::GetSettings();

    if (!$oSettings)
	{
		return 1;
	}

	if ($bPro && $bInstall)
	{
		$fgc = get_data("https://afterlogic.com/get-trial-key?productId=afterlogic-webmail-pro-9&format=json");
		$oResponse = json_decode($fgc);
		if (isset($oResponse->success) && $oResponse->success && isset($oResponse->key) && $oResponse->key !== '')
		{
			$oSettings->LicenseKey = $oResponse->key;
		}
	}
	
	if ($bInstall) {
		$oSettings->DBHost = 'localhost';
		$oSettings->DBName = $args[1];
		$oSettings->DBLogin = $args[2];
		$oSettings->DBPassword = $args[3];
	
		$bFailure = $oSettings->Save();

		$dsn = "mysql:host=".$oSettings->DBHost.";dbname=".$oSettings->DBName.";charset=UTF8";
		$pdo = false;
		try {
			$pdo = new PDO($dsn, $oSettings->DBLogin, $oSettings->DBPassword);
		} catch (PDOException $e) {
		    echo $e->getMessage()."\n";
		}

		$check1 = (strpos(mysqli_get_client_info(),"mysqlnd")!==false);
		$check2 = (strpos($pdo->getAttribute(PDO::ATTR_CLIENT_VERSION),"mysqlnd")!==false);

		if ($pdo && $check1 && $check2) {
			try {
				\Aurora\System\Api::GetModuleDecorator('Core')->CreateTables();
			} catch (Exception $e) {
				echo "WARNING! Database tables were not created. Try creating them from AdminPanel.\n";
			}
			@chmod(realpath($WEBMAIL_ROOT).'/data/settings/config.json',0777);
			@chmod(realpath($WEBMAIL_ROOT).'/data/logs',0777);
			\Aurora\System\Api::GetModuleManager()->setModuleConfigValue("Core","CsrfTokenProtection",false);
			\Aurora\System\Api::GetModuleManager()->saveModuleConfigValue("Core");

			$sHTML = \Aurora\System\Api::GetModuleManager()->getModuleConfigValue("StandardLoginFormWebclient","BottomInfoHtmlText",false);
			$sHTML = '<a href="../../../webmail/paper_lantern/index.html?mailclient=none" target="_top">WEBMAIL HOME</a><br /><br />'.$sHTML;
			\Aurora\System\Api::GetModuleManager()->setModuleConfigValue("StandardLoginFormWebclient","BottomInfoHtmlText",$sHTML);
			\Aurora\System\Api::GetModuleManager()->saveModuleConfigValue("StandardLoginFormWebclient");

			\Aurora\System\Api::GetModuleManager()->setModuleConfigValue("MailAuthCpanel","Disabled",false);
			\Aurora\System\Api::GetModuleManager()->saveModuleConfigValue("MailAuthCpanel");

			$bMailServerCreate = \Aurora\System\Api::GetModuleDecorator('Mail')->CreateServer(
				"localhost", 
				"127.0.0.1", 143, false,
				"127.0.0.1", 25, false, \Aurora\Modules\Mail\Enums\SmtpAuthType::UseUserCredentials,
				"*"
			);
		} else {
			echo "ERROR: Internal PHP doesn't have mysqlnd driver for MySQL. Make sure your cPanel is updated to the latest version.\n";
			$bFailure=0;
		}
	}
		else
	{
	    $bFailure=1;
	    try {
		\Aurora\System\Api::GetModuleDecorator('Core')->CreateTables();
	    } catch (Exception $e) {
		$bFailure=0;
	    }
	}
	$sPatchFile=$args[0]."/modules/CoreWebclient/templates/HeaderView.html";
	$sPatchFileText=file_get_contents($sPatchFile);
	if (strpos($sPatchFileText,"mailclient=none")===FALSE) {
		$sTx1="<span class=\"link\" data-bind=\"i18n: {'key': '%MODULENAME%/ACTION_SHOW_MOBILE_VERSION'}\"></span>";
		$sTx2="</span><span class=\"item logout\"><a href=\"../../../webmail/paper_lantern/index.html?mailclient=none\" class=\"link\" target=\"_top\">WEBMAIL HOME</a>";
		$sPatchFileText=str_replace($sTx1, $sTx1.$sTx2, $sPatchFileText);
		file_put_contents($sPatchFile, $sPatchFileText);
	}
	return $bFailure ? 0 : 1;
}

/**
 * @param array $args
 * @return int
 */
function configure_pro($args)
{
	return configure_webmail($args, true);
}

/**
 * @param array $args
 * @return int
 */
function configure_lite($args)
{
	return configure_webmail($args, false);
}

/**
 * @param array $args
 * @return int
 */
function check_version($args)
{
	return isset($args[0], $args[1]) && version_compare($args[0], $args[1], '>=') ? 0 : 1;
}


function get_data($url)
{
	$ch = curl_init();
	$timeout = 20;
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}