#!/usr/bin/env php
<?php

/**
 * This Software is the property of Data Development and is protected
 * by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * http://www.shopmodule.com
 *
 * @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
 * @author    D3 Data Development - Daniel Seifert <support@shopmodule.com>
 * @link      http://www.oxidmodule.com
 */

namespace D3\ModCfg;

use D3\ModCfg\Application\Model\Install\d3updateinstaller;

$bootstrapFileName = getenv('ESHOP_BOOTSTRAP_PATH');
if (!empty($bootstrapFileName)) {
    $bootstrapFileName = realpath(trim(getenv('ESHOP_BOOTSTRAP_PATH')));
} else {
    $count = 0;
    $bootstrapFileName = '../../../source/bootstrap.php';
    $currentDirectory = __DIR__ . '/';
    while ($count < 5) {
        $count++;
        if (file_exists($currentDirectory . $bootstrapFileName)) {
            $bootstrapFileName = $currentDirectory . $bootstrapFileName;
            break;
        }
        $bootstrapFileName = '../' . $bootstrapFileName;
    }
}

if (!(file_exists($bootstrapFileName) && !is_dir($bootstrapFileName))) {
    $items = [
        "Unable to find eShop bootstrap.php file.",
        "You can override the path by using ESHOP_BOOTSTRAP_PATH environment variable.",
        "\n"
    ];

    $message = implode(" ", $items);

    die($message);
}

require_once($bootstrapFileName);

ini_set('error_reporting', E_ERROR);

$status = (object)[
    'noSuccess' => false,
    'noException' => false
];

/** @var d3updateinstaller $updateInstaller */
$updateInstaller = oxNew(d3updateinstaller::class);
register_shutdown_function('D3\ModCfg\handleExit', $status, $updateInstaller);

try {
    $status->noSuccess = $updateInstaller->startModuleInstallation(false, true);
} catch (\Exception $oEx) {}

function handleExit($status, \D3\ModCfg\Application\Model\Install\d3updateinstaller $updateinstaller) {
    if (($status->noSuccess) || (!$status->noException)) {
        print("There was an error while set up modules.");
    }

    if (!$status->noException) {
        print(" Please look at `EXCEPTION_LOG.txt` for more details.".PHP_EOL);
    }

    if (($status->noException) && ($status->noSuccess)) {
        print(" Please check the state of module installation.".PHP_EOL);
    }

    if ($status->noSuccess) {
        print($updateinstaller->getErrorMessage().PHP_EOL);
    }
}

$status->noException = true;

if (!$status->noSuccess) {
    exit(2);
}
