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

/*
 * This file is part of the Symfony Standard Edition.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Florian Preusner <florian@preusner.com>
 */

$rootDir      = dirname(__DIR__);
$vendorName   = 'vendor';
$vendorDir    = $rootDir . '/' . $vendorName;
$submodule    = false;
$cloneOptions = '';
$delete       = false;
$install      = true;

$commands = array(
    'install'             => 'install vendors as specified in deps or deps.lock (recommended)', 
    'update'              => 'update vendors to their latest versions (as specified in deps)', 
    'delete'              => 'remove vendors', 
    'reinstall'           => 'delete and install', 
    'submodule:install'   => 'install vendors as submodules', 
    'submodule:update'    => 'update vendors to their latest versions (as specified in deps)', 
    'submodule:delete'    => 'remove vendors', 
    'submodule:reinstall' => 'delete and install'
);



array_shift($argv);
if (!isset($argv[0]) || in_array('help', $argv)) {
    
    $help  = "Symfony2 vendors script management.\n";
    $help .= "Specify a command to run:\n\n";

    foreach($commands as $cmd => $info) {

        $help .= str_pad($cmd, 21, ' ') . ":  $info\n";
    }
    
    exit($help . "\n");
}

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

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

if (strpos($command, 'submodule') !== false) {

    $submodule = true;
    $command   = str_replace('submodule:', '', $command);

    if(!is_dir($rootDir . '/.git')) {

        exit("This project is not a git repository. To use submodules it should be a repository :)\n");
    }
}

// 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];
    }
}

if('delete' === $command) {
    $delete  = true;
    $install = false;
}

if('reinstall' === $command) {
    $delete  = true;    
}

$newversions = array();
$deps        = parse_ini_file($rootDir.'/deps', true, INI_SCANNER_RAW);
foreach ($deps as $name => $dep) {
    // revision
    if (isset($versions[$name])) {
        $rev = $versions[$name];
    } else {
        $rev = isset($dep['version']) ? $dep['version'] : 'origin/HEAD';
    }
    
    // make sure to run commands on rootDir
    system("cd $rootDir");

    // install dir
    if($submodule) {

        $installDir = isset($dep['target']) ? $vendorName . $dep['target'] : $vendorName . '/' . $name;
    } else {

        $installDir = isset($dep['target']) ? $vendorDir . $dep['target'] : $vendorDir . '/' . $name;
    }
    
    
    
    if($delete) {

        echo "> Removing $name\n";

        if($submodule) {

            deleteSubmodule($installDir, $rootDir);
        }

        if(PHP_OS == 'WINNT') {

            system('rmdir /S /Q ' . escapeshellarg(realpath($installDir)));
        } else {

            system('rm -rf ' . escapeshellarg($installDir));
        }
    }
    
    
    if($install) {
    
        echo "> Installing/Updating $name\n";
        
         // url
        if (!isset($dep['git'])) {
            exit(sprintf('The "git" value for the "%s" dependency must be set.', $name));
        }
        $url = $dep['git'];

        if($submodule) {

            $cmd  = sprintf('git submodule add %s %s', escapeshellarg($url), escapeshellarg($installDir));
            $cmd .= ' && git submodule init';
            
        } else {
        
            $cmd = sprintf('git clone %s %s', escapeshellarg($url), escapeshellarg($installDir));
        }
            
        echo "  $cmd\n";
        
        system($cmd);        

        system(sprintf('cd %s && git fetch origin && git reset --hard %s', escapeshellarg($installDir), 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) {
    file_put_contents($rootDir.'/deps.lock', implode("\n", $newversions));
}

if($install) {

    // 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')));

    // Update assets
    system(sprintf('%s %s assets:install --symlink %s', $interpreter, escapeshellarg($rootDir.'/app/console'), escapeshellarg($rootDir.'/web')));

    // Remove the cache
    system(sprintf('%s %s cache:clear --no-warmup', $interpreter, escapeshellarg($rootDir.'/app/console')));
}




function deleteSubmodule($name, $rootDir) {

    $gitModules = $rootDir . '/.gitmodules';
    $gitConfig  = $rootDir . '/.git/config';
    
    $files = array($gitModules, $gitConfig);

    foreach($files as $file) :
    
        if(file_exists($file)) {

            $fileReturn = array();
            $found      = false;
        
            foreach(file($file) as $line) {

                if(strpos($line, '"' . $name . '"') !== false) {
                
                    $found = true;
                    continue;
                }
                
                if($found) {
                
                    if($line{0} != '[') {
                    
                        continue;
                    }
                    
                    $found = false;
                }
                
                array_push($fileReturn, $line);
            }
            
            $handle = fopen($file, 'wt');       
            
            if($handle) {
        
                fwrite($handle, implode($fileReturn));
                fclose($handle);
            }
        }
    endforeach;
    
    $cmd = "git rm --cached --force $name";
    
    echo "  $cmd\n";
    system($cmd);
}