#!/usr/bin/env php
<?php
namespace Fgm\ComposerCheck;

/**
 * Guess the path where the Composer autoloader is available.
 *
 * TODO find a better logic.
 *
 * @return string
 *   The path to the
 */
function setupAutoload($debug = FALSE) {
  $runningFrom = [
    // Straight git clone, then composer install.
    "git clone" => __DIR__ . '/../vendor',
    // Composer install as drush plugin with default config/bin.
    "composer default" => __DIR__ . '/../../../../vendor',
  ];

  foreach ($runningFrom as $kind => $location) {
    $path = "${location}/autoload.php";
    if (is_file($path) && is_readable($path)) {
      $autoloader = include_once $path;
      if ($autoloader instanceof \Composer\Autoload\ClassLoader) {
        if ($debug) {
          echo "Install appears to be: $kind\n";
        }
        break;
      }
    }
  }

  return realpath(dirname($location));
}

// TODO use options.
$all = FALSE;
$debug = TRUE;
$useYaml = TRUE;

$path = setupAutoload($debug);
if (empty($path)) {
  die("Autoloader not found.");
}
$factory = new LoaderFactory($path, $all);

$requirementsLoader = $factory->createLoader('requirements');
$requirementsLoader->load();

$lockLoader = $factory->createLoader('lock');
$lockLoader->load();

$merger = new MergeBox($requirementsLoader, $lockLoader, $all);
$merger->merge();

$reporter = $useYaml ? new YamlReporter() : new JsonReporter();
echo $reporter->report($merger);