<?php
/**
  * Copyright ETS Software Technology Co., Ltd
 *
 * NOTICE OF LICENSE
 *
 * This file is not open source! Each license that you purchased is only available for 1 website only.
 * If you want to use this file on more websites (or projects), you need to purchase additional licenses.
 * You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future.
 *
 * @author ETS Software Technology Co., Ltd
 * @copyright  ETS Software Technology Co., Ltd
 * @license    Valid for 1 website (or project) for each purchase of license
*/

use PrestaShop\Module\EtsAutoUpgrade\Tools14;

if (function_exists('date_default_timezone_set')) {
    // date_default_timezone_get calls date_default_timezone_set, which can provide warning
    $timezone = @date_default_timezone_get();
    date_default_timezone_set($timezone);
}

/**
 * Set constants & general values used by the autoupgrade.
 *
 * @param string $callerFilePath Path to the caller file. Needed as the two files are not in the same folder
*/
function autoupgrade_init_container($callerFilePath)
{
    if (PHP_SAPI === 'cli') {
        $options = getopt('', array('dir:'));
        if (isset($options['dir'])) {
            $_POST['dir'] = $options['dir'];
        }
    }

    // the following test confirm the directory exists
    if (empty($_POST['dir'])) {
        echo 'No admin directory provided (dir). 1-click upgrade cannot proceed.';
        exit(1);
    }

    // defines.inc.php can not exists (1.3.0.1 for example)
    // but we need _PS_ROOT_DIR_
    if (!defined('_PS_ROOT_DIR_')) {
        define('_PS_ROOT_DIR_', realpath($callerFilePath . '/../../'));
    }

    if (!defined('_PS_MODULE_DIR_')) {
        define('_PS_MODULE_DIR_', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR);
    }

    define('AUTOUPGRADE_MODULE_DIR', _PS_MODULE_DIR_ . 'ets_upgrade' . DIRECTORY_SEPARATOR);
    require_once AUTOUPGRADE_MODULE_DIR . '/classes/Ext/functions';
    require_once AUTOUPGRADE_MODULE_DIR . 'vendor/autoload.php';

    $dir = Tools14::safeOutput(Tools14::getValue('dir'));
    define('_PS_ADMIN_DIR_', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $dir);

    if (_PS_ADMIN_DIR_ !== realpath(_PS_ADMIN_DIR_)) {
        echo 'wrong directory: ' . $dir;
        exit(1);
    }

    $container = new \PrestaShop\Module\EtsAutoUpgrade\UpgradeContainer(_PS_ROOT_DIR_, _PS_ADMIN_DIR_);
    $container->getState()->importFromArray(empty($_REQUEST['params']) ? array() : $_REQUEST['params']);

    return $container;
}
