#!/usr/bin/env php
<?php
if (file_exists(__DIR__ . '/../../../autoload.php')) {
    require_once __DIR__ . '/../../../autoload.php';
} else {
    require_once __DIR__.'/../vendor/autoload.php';
}

try {
    $opts = \Cauditor\Utils::getopts(array(
        'a' => 'all',
        'h' => 'help',
        'p:' => 'path:',
        'r:' => 'repo:',
        'b:' => 'branch:',
        'c:' => 'commits:',
    ));

    if (isset($opts['help'])) {
        $runner = new \Cauditor\Runners\Help();
        $runner->execute();
        exit(0);
    }

    $repo = isset($opts['repo']) ? $opts['repo'] : false;
    $branch = isset($opts['branch']) ? $opts['branch'] : false;
    $path = isset($opts['path']) ? $opts['path'] : false;
    $path = $path ?: getcwd();

    if ($repo !== false) {
        if (!isset($opts['all']) && !isset($opts['commits'])) {
            // need a depth of 2 to get hash of previous commit
            exec("git clone --depth=2 $repo $path");
        } else {
            exec("git clone $repo $path");
        }
    }
    chdir("$path");

    // bootstrap
    $config = new Cauditor\Config($path, $path.DIRECTORY_SEPARATOR.'.cauditor.yml');
    $analyzer = new Cauditor\Analyzers\PDepend\Analyzer($config);
    $api = new \Cauditor\Api('https://www.cauditor.org');

    if (isset($opts['all'])) {
        $runner = new \Cauditor\Runners\All($api, $analyzer);
    } elseif (isset($opts['commits'])) {
        $commits = explode(',', $opts['commits']);
        $runner = new \Cauditor\Runners\Commits($api, $analyzer, $commits);
    } else {
        $runner = new \Cauditor\Runners\Current($api, $analyzer);
    }

    if (isset($opts['branch'])) {
        $runner->setBranch($opts['branch']);
    }

    $runner->execute();
} catch (Exception $e) {
    exit(1);
}
