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

// Utility script to setup submodules for new projects
// Running this script is optional and is not applicable
// for composer users.

$options = getopt("h::", array('help::', 'reference:'));

$reference = null;
if (isset($options['reference'])) {
	$reference = realpath($options['reference']) . DIRECTORY_SEPARATOR;
	if (!file_exists($reference)) {
		echo "\nRepository $options[reference] not found\n";
		exit(1);
	}
	echo "\nReusing repositories from $reference\n";
}

if (isset($options['help']) || isset($options['h'])) {
	echo <<< EOF

Usage: $argv[0] [-h|--help] [--reference path]

  -h | -help         Display usage information

  -r | --reference   Use existing repositories from path when available.
                     The resulting git repositories will be automatically
                     repacked to avoid dependency on the original repo.
                     Useful to save time/bandwith during the first clone.


EOF;
	exit(0);
}

$repos = array(
	'cakephp' => array(
		'url' => 'http://github.com/cakephp/cakephp',
		'target' => 'Vendor/cakephp/cakephp',
		'branch' => '2.x',
	),
	'croogo' => array(
		'url' => 'http://github.com/croogo/croogo',
		'target' => 'Vendor/croogo/croogo',
		'branch' => 'master',
	),
	'Ckeditor' => array(
		'url' => 'http://github.com/croogo/Ckeditor',
		'target' => 'Plugin/Ckeditor',
		'branch' => 'master',
	),
	'migrations' => array(
		'url' => 'http://github.com/CakeDC/migrations',
		'target' => 'Plugin/Migrations',
		'branch' => '2.2.3',
	),
	'search' => array(
		'url' => 'http://github.com/CakeDC/search',
		'target' => 'Plugin/Search',
		'branch' => '2.2.1',
	),
);

foreach ($repos as $repo => $config) {
	if (file_exists($config['target'])) {
		echo "Skipping $config[target] since it already exists.\n";
		continue;
	}
	if (file_exists($reference . $config['target'])) {
		$referenceOption = '--reference ' . $reference . $config['target'];
	} else {
		$referenceOption = null;
	}
	$cmd = sprintf('git submodule add -f %s %s %s',
		$referenceOption,
		escapeshellarg($config['url']),
		escapeshellarg($config['target'])
	);

	if ($referenceOption) {
		$cmd .= sprintf(" &&\n\tgit --git-dir %s/.git --work-tree %s repack -ad",
			escapeshellarg($config['target']),
			escapeshellarg($config['target'])
		);
		$cmd .= ' && rm .git/modules/' . $config['target'] . '/objects/info/alternates';
	}

	$cmd .= sprintf(" &&\n\tgit --git-dir %s/.git --work-tree %s checkout -f %s\n",
		escapeshellarg($config['target']),
		escapeshellarg($config['target']),
		escapeshellarg($config['branch'])
	);
	echo "$cmd\n";
	passthru($cmd);
}
