<?php
/**
 * @obfuscate_disable
 */
namespace Claromentis\Setup\Script;

use Claromentis\Setup\SetupFacade;
use Claromentis\Setup\Util;

/**
 * Load some initial content into the database.
 */
class Init
{
	/**
	 * The base path for applications.
	 *
	 * @var string
	 */
	protected $application_path;

	/**
	 * Create a new init script runner.
	 *
	 * @param string $application_path
	 */
	public function __construct($application_path)
	{
		$this->application_path = $application_path;
	}

	/**
	 * Determine whether the init script exists.
	 *
	 * @return bool
	 *
	 * @throws \Exception
	 */
	public function Exists()
	{
		$init_path = Util::GetAppInitPath($this->application_path);

		return is_readable($init_path . '/init.php') || is_readable($init_path . '/_init.php');
	}

	/**
	 * Run the init script of the given application.
	 *
	 * @param SetupFacade $setup_facade
	 *
	 * @throws \Exception
	 */
	public function Run(SetupFacade $setup_facade)
	{
		$init_path = Util::GetAppInitPath($this->application_path);

		if (!defined('INSTALL_PROGRESS'))
			define('INSTALL_PROGRESS', 1);

		$db_bak = isset($GLOBALS['db']) ? $GLOBALS['db'] : null;

		$db = $setup_facade->GetDb();
		$GLOBALS['db'] = $db;
		$db->DisableTokenCheck();

		try {
			/** @noinspection PhpUnusedLocalVariableInspection */
			$installer = $setup_facade; // variable $installer is used in init.php

			if (is_readable($init_path . '/init.php'))
				include($init_path . '/init.php');
			elseif (is_readable($init_path . '/_init.php'))
				include($init_path . '/_init.php');
		} catch (\Exception $e)
		{
			$db->EnableTokenCheck();
			$GLOBALS['db'] = $db_bak;

			throw $e;
		}

		$db->EnableTokenCheck();
		$GLOBALS['db'] = $db_bak;
	}
}
