#!/usr/bin/env php
<?php declare(strict_types=1);

if (version_compare('7.4.0', PHP_VERSION, '>')) {
    fwrite(
        STDERR,
        sprintf(
            'This version of Dvelum\DR\UI requires PHP >= 7.4.' . PHP_EOL .
            'You are using PHP %s (%s).' . PHP_EOL,
            PHP_VERSION,
            PHP_BINARY
        )
    );
    die(1);
}
echo PHP_EOL;
echo __DIR__;

$autolader = false;
foreach (array(__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
    if (file_exists($file)) {
        $autolader = $file;
        break;
    }
}

if($autolader === false){
    fwrite(
        STDERR,
        'You need to set up the project dependencies using Composer:' . PHP_EOL . PHP_EOL .
        '    composer install' . PHP_EOL . PHP_EOL .
        'You can learn all about Composer on https://getcomposer.org/.' . PHP_EOL
    );
    die(1);
}

include $autolader;

use Nette\Neon\Neon;

$workingDirectory = \getcwd();

$config = file_get_contents(__DIR__.'/drui.neon');
$config = Neon::decode($config);

if(file_exists($workingDirectory.'/drui.neon')){
    $localConfig = file_get_contents($workingDirectory.'/drui.neon');
    $localConfig = Neon::decode($localConfig);
    $config =  array_replace_recursive($config, $localConfig);
}

$userConfig = [
    'dir' => $workingDirectory,
    'registry' => $config['registry'],
    'bootstrap' => $config['bootstrap']
];

$envValue = \json_encode($userConfig);
$cmd = "export DVELUM_DR_UI_ENV='".$envValue."'  && " .
             PHP_BINARY . ' -S '.
             $config['server']['host'].':'.$config['server']['port'].
             ' -c server.ini -t '.
             __DIR__.'/public/ '.
             __DIR__.'/worker.php';

system($cmd);
exit();