<?php
/**
* @version	$Id: configure_profile.php 16251 2015-09-27 06:27:49Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2014 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
define('FULL_PATH', realpath(dirname(__FILE__) . '/..'));

final class ConfigureProfileWorkflow
{

	/**
	 * Runs the workflow.
	 *
	 * @return void
	 * @throws Exception When some of executed commands fails.
	 */
	public function run()
	{
		$this->checkPrerequisites();

		if ( !chdir(FULL_PATH) ) {
			throw new Exception('Unable to change working directory to "' . FULL_PATH . '"');
		}

		$xml = $this->runSvnCommand('info --xml');
		$info = new SimpleXMLElement($xml);

		$url = 'http://www.in-portal.com/rest/profiles.json';
		$url_params = array(
			'name' => $this->getArgument(1, 'in-portal.community'),
			'version' => basename($info->entry->url),
		);

		$json = file_get_contents($url . '?' . http_build_query($url_params));
		$profile_data = json_decode($json, true);

		if ( is_null($profile_data) ) {
			throw new Exception('Something went wrong, while queering for profile information. Please try again later.', 104);
		}

		if ( isset($profile_data['errors']) ) {
			$first_error = reset($profile_data['errors']);

			throw new Exception($first_error['message'], 105);
		}

		$svn_property_file = tempnam(sys_get_temp_dir(), 'svn_externals');
		file_put_contents($svn_property_file, $profile_data['svn:externals']);

		$this->runSvnCommand('propset svn:externals -F ' . escapeshellarg($svn_property_file) . ' .');
		echo 'Please run "svn update" on the working copy to finish the process.' . PHP_EOL;
	}

	/**
	 * Checks prerequisites.
	 *
	 * @return void
	 * @throws Exception When one of prerequisites are not met.
	 */
	protected function checkPrerequisites()
	{
		if ( PHP_SAPI !== 'cli' ) {
			throw new Exception('This script is intended to be used from command-line only !', 100);
		}

		try {
			$this->runSvnCommand('info ' . escapeshellarg(FULL_PATH));
		}
		catch ( Exception $e ) {
			throw new Exception('The "' . FULL_PATH . '" must be an SVN working copy or "svn" binary is not in the PATH', 102);
		}

		$allow_url_fopen = ini_get('allow_url_fopen');

		if ( strtolower($allow_url_fopen) === 'off' || (int)$allow_url_fopen === 0 ) {
			throw new Exception('Temporarily enable "allow_url_fopen" setting in "php.ini" for script to work', 103);
		}
	}

	/**
	 * Executes SVN command and returns the result.
	 *
	 * @param string $arguments Command arguments.
	 *
	 * @return string
	 * @throws Exception If something goes wrong.
	 */
	protected function runSvnCommand($arguments)
	{
		$exit_code = 0;
		$output = array();
		$command = 'svn ' . $arguments . ' 2>&1';

		exec($command, $output, $exit_code);

		if ( $exit_code !== 0 ) {
			throw new Exception('Command "' . $command . '" failed with ' . $exit_code . ' exit code');
		}

		return implode("\n", $output);
	}

	/**
	 * Returns passed argument value.
	 *
	 * @param integer $index Argument index.
	 * @param mixed $default Default value.
	 *
	 * @return mixed
	 */
	protected function getArgument($index, $default = null)
	{
		if ( $index < $_SERVER['argc'] ) {
			return $_SERVER['argv'][$index];
		}

		return $default;
	}

}


try {
	$workflow = new ConfigureProfileWorkflow();
	$workflow->run();
}
catch ( Exception $e ) {
	echo $e->getMessage().PHP_EOL;
	exit($e->getCode());
}