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

require __DIR__ . '/../bootstrap/autoload.php';

use MAKS\Velox\Backend\Config;


if (!Config::get('cli.app-serve.enabled', false)) {
    echo 'Command is disabled!', PHP_EOL;
    exit(1);
}


$server = [
    'host'   => Config::get('cli.app-serve.args.host', 'localhost'),
    'port'   => Config::get('cli.app-serve.args.port', 8000),
    'root'   => Config::get('cli.app-serve.args.root', dirname(__DIR__)),
    'router' => Config::get('cli.app-serve.args.root', dirname(__DIR__)) . '/server.php',
];

$command = vsprintf('php -S %s:%d -t %s %s', $server);


$routerFile = $server['router'];
$routerContent = <<<PHP
<?php
// This is an autogenerated file used for routing with development server.
// You can safely delete this file if you wish to.
// It will get regenerated again when running "php bin/app-serve".

\$root = '{$server["root"]}';

\$blacklisted = '/\/bin\/|\/storage\/|\.php|\.phtml/i';
\$requestPath = urldecode(parse_url(\$_SERVER['REQUEST_URI'], PHP_URL_PATH));

if (!preg_match(\$blacklisted, \$requestPath)) {
    return false;
}

require \$root . '/index.php';
PHP;


if (file_exists($routerFile) == false || file_get_contents($routerFile) !== $routerContent) {
    file_put_contents($routerFile, $routerContent);
}


echo shell_exec($command);


echo 'OK!', PHP_EOL;
exit(0);
