#!/usr/bin/env php
<?php
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

// Deployer constants
define('DEPLOYER', true);
define('DEPLOYER_BIN', __FILE__);

// Check for php7
if (!defined('PHP_MAJOR_VERSION') || PHP_MAJOR_VERSION < 7) {
    fwrite(
        STDERR,
        'Upgrade to php7' . PHP_EOL .
        'Deployer 5.x supports only php7 and above.' . PHP_EOL .
        'If you want to use older php version use Deployer 4.x' . PHP_EOL
    );
    exit(1);
}

// Detect deploy.php script
$options = getopt('f::', ['file::']);
$userSpecifiedFile = null;

if (isset($options['f'])) {
    $userSpecifiedFile = $options['f'];
} elseif (isset($options['file'])) {
    $userSpecifiedFile = $options['file'];
}

if (empty($userSpecifiedFile)) {
    $fOptIndex = array_search('-f', $argv);
    $fileOptIndex = array_search('--file', $argv);

    if ($fOptIndex && $fOptIndex + 1 < count($argv)) {
        $userSpecifiedFile = $argv[$fOptIndex + 1];
    } elseif ($fileOptIndex && $fileOptIndex + 1 < count($argv)) {
        $userSpecifiedFile = $argv[$fileOptIndex + 1];
    }
}

if (empty($userSpecifiedFile)) {
    $deployFile = getcwd() . '/deploy.php';

    if (!is_readable($deployFile)) {
        $currentDir = getcwd();
        $count = 0;
        do {
            $currentDir = dirname($currentDir);
            $deployFile = $currentDir . '/deploy.php';
            $count++;
        } while (!is_readable($deployFile) && $count < 100);
    }
} else {
    $deployFile = ($userSpecifiedFile[0] === '/' ? '' : getcwd() . '/') . $userSpecifiedFile;
}

$deployFilePath = dirname($deployFile);

// Detect source location

$autoload = [
    $deployFilePath . '/vendor/autoload.php',
    __DIR__ . '/../../../autoload.php',
    __DIR__ . '/../vendor/autoload.php'
];

$includes = [
    $deployFilePath . '/vendor/deployer/deployer',
    __DIR__ . '/../../../deployer/deployer',
    __DIR__ . '/../'
];

$loaded = false;
$includePath = false;
$vendorDir = false;

for ($i = 0; $i < count($autoload); $i++) {
    if (file_exists($autoload[$i]) && file_exists($includes[$i])) {
        require $autoload[$i];
        $vendorDir = dirname($autoload[$i]);
        $includePath = $includes[$i];
        $loaded = true;
        break;
    }
}

if (!$loaded) {
    fwrite(
        STDERR,
        'You need to set up the project dependencies using the following commands:' . PHP_EOL .
        'wget http://getcomposer.org/composer.phar' . PHP_EOL .
        'php composer.phar install' . PHP_EOL
    );
    exit(1);
}

// Setup include path
set_include_path($includePath . PATH_SEPARATOR . get_include_path());

// Detect version
$version = 'master';

$installedFile = $vendorDir . '/composer/installed.json';
if (is_readable($installedFile)) {
    $installed = json_decode(file_get_contents($installedFile), true);
    $packages = $installed['packages'] ?? $installed;

    foreach ($packages as $package) {
        if ($package['name'] === 'deployer/deployer') {
            $version = $package['version'];
            break;
        }
    }
}

$method = new ReflectionMethod('Deployer\Deployer', 'run');
if (!$method->isStatic()) {
    fwrite(
        STDERR,
        'You need to update Deployer to the latest version:' . PHP_EOL .
        PHP_EOL .
        '  dep self-update' . PHP_EOL .
        PHP_EOL .
        'Or use composer installed version:' . PHP_EOL .
        PHP_EOL .
        '  php vendor/bin/dep' . PHP_EOL .
        PHP_EOL

    );
    exit(1);
}

\Deployer\Deployer::run($version, $deployFile);
