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

declare(strict_types=1);

use DI\ContainerBuilder;
use MeshVault\Config\AppConfig;
use MeshVault\Console\Console;
use MeshVault\Console\ConsoleServices;
use MeshVault\Console\LazyConsoleServices;

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, 'meshvault must be run from the command line.' . PHP_EOL);
    exit(1);
}

require dirname(__DIR__) . '/vendor/autoload.php';

// Built on first use so help and usage errors never require configuration.
$services = new LazyConsoleServices(static function (): ConsoleServices {
    $builder = new ContainerBuilder();
    $definitions = require dirname(__DIR__) . '/config/container.php';
    $builder->addDefinitions($definitions(AppConfig::fromEnvironment(getenv())));
    return $builder->build()->get(ConsoleServices::class);
});

$stopping = false;
$stopRequested = static function () use (&$stopping): bool {
    if (function_exists('pcntl_signal_dispatch')) {
        pcntl_signal_dispatch();
    }
    return $stopping;
};
if (function_exists('pcntl_signal')) {
    $handler = static function () use (&$stopping): void {
        $stopping = true;
    };
    pcntl_signal(SIGTERM, $handler);
    pcntl_signal(SIGINT, $handler);
}

$console = new Console(
    $services,
    STDOUT,
    STDERR,
    static function (int $seconds) use ($stopRequested): void {
        // Poll each second so a signal is honoured without waiting out the interval.
        for ($elapsed = 0; $elapsed < $seconds && !$stopRequested(); $elapsed++) {
            sleep(1);
        }
    },
    $stopRequested,
);

exit($console->run(array_slice($argv, 1)));
