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

if ('YES' === getenv('CHECKSTYLE')) {
        runCommand('./vendor/bin/checkstyle');
}

if ('YES' === getenv('COVERAGE')) {
        runCommand('./vendor/bin/runcoverage');
        runCommand('ln -s Classes src');
        runCommand('./vendor/bin/coveralls');
} else {
        runCommand('./vendor/bin/runtests');
}

function runCommand($command) {
        global $argv;
        $path = dirname($argv[0]) . '/';
        $root = substr($path, 0, -11);
        $root = realpath($root);

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

        $process = proc_open($command, $descriptors, $pipes, $root);
        fclose($pipes[0]);

        while ($char = fread($pipes[1], 8)) {
                echo $char;
        }

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

        $exit = proc_close($process);
        if (0 < $exit) {
                echo $errors;
                echo PHP_EOL;
		exit($exit);
        }
}

