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

use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
use Illuminate\Foundation\Application;
use Parallax\Console\Kernel;
use Parallax\PhpSource\Launcher;
use Parallax\PhpSource\ZhqlLauncher;
use Symfony\Component\Console\Input\ArgvInput;

// PHP source lifecycle commands must remain usable without application boot.
// In particular, elevated activation/restore must not run Laravel as root.
if (($argv[1] ?? null) === 'php') {
    require_once __DIR__.'/modules/parallax/src/PhpSource/Launcher.php';

    exit(Launcher::run(__DIR__, array_slice($argv, 2)));
}

if (($argv[1] ?? null) === 'klaxon') {
    require_once __DIR__.'/modules/parallax/src/PhpSource/ZhqlLauncher.php';

    exit(ZhqlLauncher::run(__DIR__, array_slice($argv, 2)));
}

define('LARAVEL_START', microtime(true));

// Register the Composer autoloader. Composer's bin proxy names the host
// project's autoloader when this package is installed as a dependency.
$autoloadPath = $GLOBALS['_composer_autoload_path']
    ?? (is_file(__DIR__.'/vendor/autoload.php') ? __DIR__.'/vendor/autoload.php' : __DIR__.'/../../autoload.php');

if (! is_file($autoloadPath)) {
    fwrite(STDERR, "Slipstream dependencies are missing. Run composer install first.\n");

    exit(1);
}

require $autoloadPath;

$vendorPath = realpath(dirname($autoloadPath));

// As a dependency, run inside the host Laravel application, which registers the
// Slipstream commands. This checkout's own App namespace is shadowed there.
if ($vendorPath !== realpath(__DIR__.'/vendor')) {
    $hostBootstrap = dirname($vendorPath).'/bootstrap/app.php';

    if (! is_file($hostBootstrap)) {
        fwrite(STDERR, 'Slipstream installed as a dependency requires a Laravel application at '.dirname($vendorPath).".\n");

        exit(1);
    }

    /** @var Application $app */
    $app = require_once $hostBootstrap;

    exit($app->handleCommand(new ArgvInput));
}

// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$app->singleton(ConsoleKernelContract::class, Kernel::class);

$status = $app->handleCommand(new ArgvInput);

exit($status);
