#!/usr/bin/env php
<?php
use Garden\Cli\Cli;
use Aivec\WordPress\Codeception;
use Aivec\WordPress\Codeception\CodeceptDocker;

require_once 'vendor/autoload.php';

// first, check caller
if (!CodeceptDocker::invokedFromProjectRoot()) {
    echo "\r\n";
    echo 'FATAL: you can only use this binary from the root of your project.';
    echo "\r\n";
    exit(1);
}

// Define a cli with commands.
$cli = Cli::create()
    ->command('create-config')
    ->description('Create codecept-docker.json config file in project directory.')
    ->opt('namespace:n', 'Prefix for testing containers', false, 'string')
    ->opt('type:t', 'Project type. Must be one of "plugin", "theme", or "library"', true, 'string')
    ->command('init')
    ->description('Create Docker containers and Codeception scaffolding')
    ->command('start')
    ->description('Start stopped containers')
    ->command('stop')
    ->description('Stop running containers')
    ->command('down')
    ->description('Stops and removes containers. NOTE: you will have to call "init" again if you do this')
    ->command('update')
    ->description('Updates wordpress and wp-cli Docker images to latest')
    ->command('codecept')
    ->description('Calls and passes args to codecept script from within Docker container')
    ->command('wp-cli')
    ->description('Runs and passes command/arguments to wp-cli container for Docker installs');

// Parse and return cli args.
$args = $cli->parse($argv, true);

if ($argv[1] !== 'create-config') {
    if (!file_exists(CodeceptDocker::getAbsPath() . '/codecept-docker.json')) {
        echo "\r\n";
        echo 'FATAL: codecept-docker.json does not exist in project directory. Create one with "aivec-codecept create-config --type=<type>"';
        echo "\r\n";
        exit(1);
    }
}

switch ($argv[1]) {
    case 'create-config':
        Codeception\CLI\CreateConfig::run($args->getOpt('type'), $args->getOpt('namespace'));
        break;
    case 'init':
        (new Codeception\CLI\Docker(new CodeceptDocker()))->init();
        break;
    case 'start':
        (new Codeception\CLI\Docker(new CodeceptDocker()))->start();
        break;
    case 'stop':
        (new Codeception\CLI\Docker(new CodeceptDocker()))->stop();
        break;
    case 'down':
        (new Codeception\CLI\Docker(new CodeceptDocker()))->down();
        break;
    case 'update':
        (new Codeception\CLI\Docker(new CodeceptDocker()))->updateImages();
        break;
    case 'codecept':
        (new Codeception\CLI\Docker(new CodeceptDocker()))->codecept(join(' ', array_slice($argv, 2)));
        break;
    case 'wp-cli':
        (new Codeception\CLI\Docker(new CodeceptDocker()))->wpcli(join(' ', array_slice($argv, 2)));
        break;
}
