#!/usr/bin/env php
<?php
define('GRAV_CLI', true);

if (!file_exists(__DIR__ . '/../vendor')) {
    require_once __DIR__ . '/../system/src/Grav/Common/Composer.php';
}

use Grav\Common\Composer;

if (!file_exists(__DIR__ . '/../vendor')) {
    // Before we can even start, we need to run composer first
    $composer = Composer::getComposerExecutor();
    echo "Preparing to install vendor dependencies...\n\n";
    echo system($composer . ' --working-dir="' . __DIR__ . '/../" --no-interaction --no-dev --prefer-dist -o install');
    echo "\n\n";
}

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Grav\Common\Grav;
use Grav\Common\Filesystem\Folder;

$autoload = require_once(__DIR__ . '/../vendor/autoload.php');

if (version_compare($ver = PHP_VERSION, $req = GRAV_PHP_MIN, '<')) {
    exit(sprintf("You are running PHP %s, but Grav needs at least PHP %s to run.\n", $ver, $req));
}

if (!ini_get('date.timezone')) {
    date_default_timezone_set('UTC');
}

if (!file_exists(ROOT_DIR . 'index.php')) {
    exit('FATAL: Must be run from ROOT directory of Grav!');
}

$grav = Grav::instance(array('loader' => $autoload));
$grav['config']->init();
$grav['streams'];
$grav['plugins']->init();
$grav['themes']->init();

$app     = new Application('Grav Plugins Commands', GRAV_VERSION);
$pattern = '([A-Z]\w+Command\.php)';

// get arguments and  strip the application name
if (null === $argv) {
    $argv = $_SERVER['argv'];
}

$bin  = array_shift($argv);
$name = array_shift($argv);
$argv = array_merge([$bin], $argv);

$input = new ArgvInput($argv);

$plugin = $grav['plugins']->get($name);

$output = new ConsoleOutput();
$output->getFormatter()->setStyle('red', new OutputFormatterStyle('red', null, array('bold')));
$output->getFormatter()->setStyle('white', new OutputFormatterStyle('white', null, array('bold')));

if (!$name) {
    $output->writeln('');
    $output->writeln("<red>Usage:</red>");
    $output->writeln("  {$bin} [slug] [command] [arguments]");
    $output->writeln('');
    $output->writeln("<red>Example:</red>");
    $output->writeln("  {$bin} error log -l 1 --trace");
    $list = Folder::all('plugins://', ['compare' => 'Pathname', 'pattern' => '/\/cli\/' . $pattern . '$/usm']);

    if (count($list)) {
        $available = [];
        $output->writeln('');
        $output->writeln('<red>Plugins with CLI available:</red>');
        foreach ($list as $index => $entry) {
            $split = explode('/', $entry);
            $entry = array_shift($split);
            $index = str_pad($index++ + 1, 2, '0', STR_PAD_LEFT);

            if (in_array($entry, $available)) {
                continue;
            }

            $available[] = $entry;
            $output->writeln('  ' . $index . ". <red>" . str_pad($entry, 15) . "</red> <white>${bin} ${entry} list</white>");
        }
    }

    exit;
}

if ($plugin === null) {
    $output->writeln("<red>Grav Plugin <white>'{$name}'</white> is not installed</red>");
    exit;
}

$path = 'plugins://' . $name . '/cli';

try {
    $commands = Folder::all($path, ['compare' => 'Filename', 'pattern' => '/' . $pattern . '$/usm']);
} catch (\RuntimeException $e) {
    $output->writeln("<red>No Console Commands for <white>'{$name}'</white> where found in <white>'{$path}'</white></red>");
    exit;
}

foreach ($commands as $command_path) {
    require_once "plugins://{$name}/cli/{$command_path}";

    $command_class = 'Grav\Plugin\Console\\' . preg_replace('/.php$/', '', $command_path);
    $command = new $command_class();
    $app->add($command);
}

$app->run($input);
