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

/*
 * This file is an altered version of the original symfony2 vendor script.
 *   reference : https://github.com/symfony/symfony-standard/blob/master/bin/vendors
 *
 *  Main differences :
 *    - use git submodule : https://git.wiki.kernel.org/index.php/GitSubmoduleTutorial
 *    - remove symfony2 tasks call
 *    - user can provide a deps name to update/install
 *
 * authors :
 *   Fabien Potencier <fabien@symfony.com>
 *   Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */

$rootDir   = dirname(__DIR__);
$vendorDir = $rootDir.'/vendor';
$deps      = parse_ini_file($rootDir.'/deps', true, INI_SCANNER_RAW);

$bin = array_shift($argv);
if (!isset($argv[0])) {
    echo_message(<<<EOF
Symfony2 vendors script management (using git submodule version).

Specify a command to run: $bin install|update [deps name]

 install: install vendors as specified in deps or deps.lock (recommended)
 update:  update vendors to their latest versions (as specified in deps)

EOF
    );

   echo_message("Deps available:");
   foreach ($deps as $name => $options) {
      echo_message(sprintf(" - %s", $name));
   }

   exit(1);
}

if (!in_array($command = array_shift($argv), array('install', 'update'))) {
    exit(sprintf("Command \"%s\" does not exist.\n", $command));
}

if (!is_dir($vendorDir)) {
    mkdir($vendorDir, 0777, true);
}

if (count($argv) == 0) {
    $bundle = 'all';
} else {
    $bundle = array_shift($argv);
}

// versions
$versions = array();
if ('install' === $command && file_exists($rootDir.'/deps.lock')) {
    foreach (file($rootDir.'/deps.lock', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $parts = array_values(array_filter(explode(' ', $line)));
        if (2 !== count($parts)) {
            exit(sprintf('The deps version file is not valid (near "%s")', $line));
        }
        $versions[$parts[0]] = $parts[1];
    }
}

chdir($rootDir);

/**
 * @param $cmd
 * @return void
 */
function exec_command($cmd)
{
    echo sprintf("executing : `%s`\n", $cmd);
    $return = null;
    passthru($cmd, $return);

    if ($return !== 0) {
        throw new \RuntimeException(sprintf('The command failed %s', $cmd));
    }
}

function echo_message($message)
{
    echo sprintf("%s\n", $message);
}

$newversions = array();
foreach ($deps as $name => $dep) {
    if ($bundle != 'all' && $name != $bundle) {
        $run = false;
    } else {
        $run = true;
    }

    // revision
    if (isset($versions[$name])) {
        $rev = $versions[$name];
    } else {
        $rev = isset($dep['version']) ? $dep['version'] : 'origin/HEAD';
    }

    // install dir
    $installDir = isset($dep['target']) ? $vendorDir.'/'.$dep['target'] : $vendorDir.'/'.$name;
    $relativeInstallDir = str_replace($rootDir.'/', '', $installDir);

    // url
    if (!isset($dep['git'])) {
        exit(sprintf('The "git" value for the "%s" dependency must be set.', $name));
    }

    $url = $dep['git'];

    if ($run) {
        $status = system(sprintf('cd %s && git status --porcelain', escapeshellarg($installDir)));
        if (!empty($status)) {
            exit(sprintf('"%s" has local modifications. Please revert or commit/push them before running this command again.', $name));
        }
        echo_message("\n> Installing/Updating $name");

        if (!is_dir($installDir)) {
            exec_command(sprintf('git submodule -q add %s %s', escapeshellarg($url), escapeshellarg($relativeInstallDir)));
        }

        exec_command(sprintf('git submodule -q update --init %s', escapeshellarg($relativeInstallDir)));
        exec_command(sprintf('cd %s && git fetch -q origin && git reset --hard %s', escapeshellarg($relativeInstallDir), escapeshellarg($rev)));
    }

    if ('update' === $command) {
        ob_start();
        system(sprintf('cd %s && git log -n 1 --format=%%H', escapeshellarg($installDir)));
        $newversions[] = trim($name.' '.ob_get_clean());
    }
}

// update?
if ('update' === $command) {
    echo_message('Update deps.lock file');
    file_put_contents($rootDir.'/deps.lock', implode("\n", $newversions));
}

// php on windows can't use the shebang line from system()
$interpreter = PHP_OS == 'WINNT' ? 'php.exe' : '';

// Update the bootstrap files
system(sprintf('%s %s', $interpreter, escapeshellarg($rootDir.'/bin/build_bootstrap.php')));

echo_message("\ndone!");
