#!/usr/bin/env php
<?php
/**
 * Bulk command to perform style validation, unit testing
 * and git commit validation.
 */

/**
 * @param string $message
 * @param integer $code
 */
function exitWithError($message, $code = 1) {
	echo '!! ERROR !!';
	echo PHP_EOL;
	echo PHP_EOL;
	echo $message;
	echo PHP_EOL;
	exit($code);
}

echo PHP_EOL;

$checkers = array('checkstyle', 'runtests');
$executables = array_merge(array('phpunit', 'phpcs'), $checkers);

// Step 1: determine calling origin:
// Resolve the path to the ./vendor/bin/ folder that contains other scripts:
$path = dirname($argv[0]) . '/';
$root = substr($path, 0, -11);
$root = realpath($root);

// Step 2: Validate that this path is correct:
$standardPathWarning = 'Path "%s" does not appear to contain an executable "phpunit" binary. Please make sure you called the ' .
	'script using the path ./vendor/bin/make from the root of your project folder';

foreach ($executables as $expectedExecutable) {
	$executable = $path . $expectedExecutable;
	if (FALSE === is_executable(realpath($executable))) {
		exitWithError(sprintf($standardPathWarning, $path, $expectedExecutable), 2);
	}
}

// Step 3: check that the hooks are in place, if not, create them:
$postCommitScript = $root . '/.git/hooks/post-commit';
if (TRUE === file_exists($postCommitScript)) {
	unlink($postCommitScript);
}
$preCommitScript = $root . '/.git/hooks/pre-commit';
file_put_contents($preCommitScript, '#!/bin/sh' . PHP_EOL . './vendor/bin/make');
chmod($preCommitScript, 0755);
$messageScript = $root . '/.git/hooks/commit-msg';
file_put_contents($messageScript, file_get_contents($root . '/vendor/fluidtypo3/development/hooks/commit-msg'));
chmod($messageScript, 0755);
$prepareScript = $root . '/.git/hooks/prepare-commit-msg';
file_put_contents($prepareScript, file_get_contents($root . '/vendor/fluidtypo3/development/hooks/prepare-commit-msg'));
chmod($prepareScript, 0755);


// Step 4: execute each of the dedicated checkers:
foreach ($checkers as $checker) {
	echo '++ Running: ' . $checker;
	echo PHP_EOL;
	echo PHP_EOL;

	$descriptors = array(
		array("pipe", "r"),
		array("pipe", "w"),
		array("pipe", "r")
	);
	$pipes = array();

	$process = proc_open($path . $checker, $descriptors, $pipes);
	fclose($pipes[0]);

	while ($threeChars = fread($pipes[1], 24)) {
		echo $threeChars;
	}

	fclose($pipes[1]);

	$errors = stream_get_contents($pipes[2]);
	fclose($pipes[2]);

	$exit = proc_close($process);

	if (0 < $exit) {
		exitWithError($errors, $exit);
	}
	echo PHP_EOL;
}

echo '++ All checks and tests completed succesfully!';
echo PHP_EOL;

exit(0);
