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

use Grav\Common\Composer;
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;

\define('GRAV_CLI', true);
\define('GRAV_REQUEST_TIME', microtime(true));

if (!file_exists(__DIR__ . '/../vendor/autoload.php')){
    // Before we can even start, we need to run composer first
    require_once __DIR__ . '/../system/src/Grav/Common/Composer.php';

    $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";
}

$autoload = require __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(GRAV_ROOT . '/index.php')) {
    exit('FATAL: Must be run from ROOT directory of Grav!');
}

$climate = new League\CLImate\CLImate;
$climate->arguments->add([
    'environment' => [
        'prefix'        => 'e',
        'longPrefix'    => 'env',
        'description'   => 'Configuration Environment',
        'defaultValue'  => 'localhost'
    ]
]);
$climate->arguments->parse();

$environment = $climate->arguments->get('environment');

$grav = Grav::instance(array('loader' => $autoload));
$grav->setup($environment);

$grav['config']->init();
$grav['uri']->init();
$grav['users'];
$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);

/** @var \Grav\Common\Data\Data $plugin */
$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', 'levels' => 2]);

    $total = 0;
    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);
            $total = str_pad($total++ + 1, 2, '0', STR_PAD_LEFT);
            if (\in_array($entry, $available, true)) {
                $total--;
                continue;
            }

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

    exit;
} else {
    if (is_null($plugin)) {
        $output->writeln('');
        $output->writeln("<red>$name plugin not found</red>");
        die;
    }

    if (!$plugin->enabled) {
        $output->writeln('');
        $output->writeln("<red>$name not enabled</red>");
        die;
    }
}

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', 'levels' => 1]);
} 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) {
    $full_path = $grav['locator']->findResource("plugins://{$name}/cli/{$command_path}");
    require_once $full_path;

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

$app->run($input);
