#!/usr/bin/env php
<?php
declare(strict_types=1);
error_reporting(E_ALL);

$unix = DIRECTORY_SEPARATOR == '/';
array_shift($argv);

if (isset($argv[0]) && $argv[0] == 'kill')
{
    if ($unix) {
        shell_exec('kill -9 $(lsof -ti tcp:4444)');
    } else {
        system("taskkill /F /IM \"chromedriver.exe\" /T & taskkill /F /IM \"geckodriver.exe\" /T");
        shell_exec('for /f "tokens=5" %a in (\'netstat -aon ^| find ":4444" ^| find "LISTENING"\') do taskkill /f /pid %a');
    }

    return;
}

// Check if selenium server is already running.
$selenium = @fsockopen('127.0.0.1', 4444);
if ($selenium !== false)
{
    fclose($selenium);
}
else
{
    $path     = '{{driver-path}}' . DIRECTORY_SEPARATOR;
    $log      = '{{log-path}}' . DIRECTORY_SEPARATOR . 'selenium.log';
    $pipe_log = '{{log-path}}' . DIRECTORY_SEPARATOR . 'output.log';
    $server   = 'selenium-server-standalone-3.141.59.jar';

    if ($unix) {
        // firefox and chrome driver path for Linux
        $drivers = "-Dwebdriver.gecko.driver=\"{$path}geckodriver\" -Dwebdriver.chrome.driver=\"{$path}chromedriver\"";
        shell_exec("java -jar $drivers {$path}{$server} -log {$log} > {$pipe_log} 2>&1 &");
    } else {
        // firefox and chrome driver path for Windows.
        $drivers = "-Dwebdriver.gecko.driver=\"{$path}geckodriver.exe\" -Dwebdriver.chrome.driver=\"{$path}chromedriver.exe\"";
        pclose(popen("start /B java -jar {$drivers} {$path}{$server} -log {$log} >{$pipe_log} >>{$pipe_log} 2>&1", 'r'));
    }
    // Make sure selenium is running.
    sleep(1);
}

system(str_replace('/', DIRECTORY_SEPARATOR, 'vendor/bin/behat --colors ' ) . implode(' ', $argv));
