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

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

/**
 * Runs uninstall scripts.
 */
class Uninstall
{
	/**
	 * The path for the application.
	 *
	 * @var string
	 */
	protected $application_path;

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

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

		return is_readable($init_path . '/uninstall.php');
	}

	/**
	 * Run the given application's uninstall script.
	 *
	 * @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 uninstall.php

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

			throw $e;
		}

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