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

require_once __DIR__ . '/../../autoload.php';


$install_path = $argv[1] ?? null;


// Get installation root path
if (\is_null($install_path))
{
    $reflection   = new \ReflectionClass(Composer\Autoload\ClassLoader::class);
    $install_path =  dirname($reflection->getFileName(), 3);
}
else
{
    $install_path = ltrim($install_path, '-path=');
}

// Check if any of the expected test direcotry exits and has a writable permission.
$test_directory = '';
$found_test_dir = false;
foreach (['test', 'tests', 'Test', 'Tests'] as $director_name)
{
    if (is_dir($test_directory = "{$install_path}/{$director_name}"))
    {
        if (! is_writable($test_directory)) {
            throw new ErrorException("{$test_directory} is not writable.");
        }

        $found_test_dir = true;
        break;
    }
}

// If no expected test directory exist, we want to make sure that the app root path is writable.
if (! $found_test_dir)
{
    if (! is_dir($test_directory = "{$install_path}/Tests") && ! is_writable($install_path)) {
        throw new ErrorException("{$install_path} is not writable.");
    }
}


echo "Setting up files at \"{$test_directory}\"\n";

! is_dir($screenshot_path = "{$test_directory}/behat/_screenshots") && mkdir($screenshot_path, 0777, true);
! is_dir($logs_path       = "{$test_directory}/behat/_logs")        && mkdir($logs_path, 0777, true);
! is_dir($feature_path    = "{$test_directory}/behat/features")     && mkdir($feature_path, 0777, true);
! is_dir($bootstrap_path  = "{$test_directory}/behat/bootstrap")    && mkdir($bootstrap_path, 0777, true);

touch("{$logs_path}/.gitkeep");
touch("{$screenshot_path}/.gitkeep");
copy(__DIR__ . '/search.feature', "{$feature_path}/search.feature");
copy(__DIR__ . '/FeatureContext.template', "{$bootstrap_path}/FeatureContext.php");


file_put_contents("{$install_path}/behat", str_replace(
    ['{{driver-path}}', '{{log-path}}'],
    [__DIR__ . '/drivers', $logs_path],
    file_get_contents(__DIR__ . '/behat')
));

file_put_contents("{$install_path}/behat.yml", str_replace(
    ['{{bootrap-path}}', '{{features-path}}'],
    [$bootstrap_path, $feature_path],
    file_get_contents(__DIR__ . '/behat.yml')
));

echo "Setup completed.\n\n";