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

declare(strict_types=1);

use Composer\InstalledVersions;

$autoload = (string) realpath(is_string($_composer_autoload_path ?? null) ? $_composer_autoload_path : __DIR__.'/../vendor/autoload.php');
require $autoload;

if (in_array($argv[1] ?? null, ['-h', '--help'], true)) {
    echo 'Usage: scaleway-serve [<host>:<port>]  (default: 127.0.0.1:8000)', \PHP_EOL;
    echo 'A POST on '.JDecool\ScalewayRuntime\Emulator::CRON_PATH.' is a CRON Invocation whose arguments are the request body.', \PHP_EOL;
    exit(0);
}

$address = $argv[1] ?? '127.0.0.1:8000';
$handlerFile = realpath(InstalledVersions::getRootPackage()['install_path']).'/handler.php';
if (!is_file($handlerFile)) {
    fwrite(\STDERR, "{$handlerFile} is missing: run vendor/bin/scaleway-init first.".\PHP_EOL);
    exit(1);
}

// A Unix socket in a private directory: no port to race for, and other local users cannot send Events.
$socketDir = sys_get_temp_dir().'/scaleway-serve-'.bin2hex(random_bytes(4));
if (!mkdir($socketDir, 0o700)) {
    exit(1);
}
$socket = 'unix://'.$socketDir.'/warm-process.sock';
register_shutdown_function(static function () use ($socketDir): void {
    @unlink($socketDir.'/warm-process.sock');
    @rmdir($socketDir);
});

/**
 * @param list<string>               $command
 * @param array<string, string>|null $env
 *
 * @return resource
 */
function start(array $command, ?array $env = null)
{
    $process = proc_open($command, [\STDIN, \STDOUT, \STDERR], $pipes, null, $env);
    if (false === $process) {
        fwrite(\STDERR, 'Cannot start '.implode(' ', $command).\PHP_EOL);
        exit(1);
    }

    return $process;
}

// The Handler runs prod when APP_ENV is unset, to keep debug pages off the platform; locally they are wanted.
if (!getenv('APP_ENV')) {
    putenv('APP_ENV=dev');
}

$startWarmProcess = static function () use ($handlerFile, $socket) {
    $warmProcess = start([\PHP_BINARY, __DIR__.'/../resources/emulator/warm-process.php', $handlerFile, $socket]);
    // Waits until it listens, so the first requests do not find the socket closed.
    for ($i = 0; $i < 100 && proc_get_status($warmProcess)['running']; ++$i) {
        if (false !== $connection = @stream_socket_client($socket)) {
            fclose($connection);
            break;
        }
        usleep(50_000);
    }

    return $warmProcess;
};

$warmProcess = $startWarmProcess();
$server = start(
    [\PHP_BINARY, '-d', 'enable_post_data_reading=0', '-d', 'expose_php=0', '-d', 'default_mimetype=', '-S', $address, __DIR__.'/../resources/emulator/router.php'],
    ['SCALEWAY_EMULATOR_AUTOLOAD' => $autoload, 'SCALEWAY_EMULATOR_SOCKET' => $socket] + getenv(),
);
// Children outlive a killed parent, so a SIGTERM would leave the port busy and the Warm Process running.
if (function_exists('pcntl_async_signals')) {
    pcntl_async_signals(true);
    foreach ([\SIGINT, \SIGTERM] as $signal) {
        pcntl_signal($signal, static function () use (&$warmProcess, $server): never {
            proc_terminate($warmProcess);
            proc_terminate($server);
            exit(0);
        });
    }
}
fwrite(\STDERR, "Emulator listening on http://{$address}, Warm Process pid ".proc_get_status($warmProcess)['pid'].', CRON triggers on POST '.JDecool\ScalewayRuntime\Emulator::CRON_PATH.\PHP_EOL);

while (($status = proc_get_status($server))['running']) {
    // A dead Warm Process is replaced, as the platform starts a new instance after a crash.
    if (!proc_get_status($warmProcess)['running']) {
        $warmProcess = $startWarmProcess();
        fwrite(\STDERR, 'Emulator: the Warm Process exited, started a new one with pid '.proc_get_status($warmProcess)['pid'].\PHP_EOL);
        // Keeps an application that cannot even load from flooding the console.
        sleep(1);
    }
    usleep(200_000);
}
proc_terminate($warmProcess);
exit($status['exitcode']);
