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

setlocale(LC_ALL, ['en_GB.utf8', 'en_GB']);
date_default_timezone_set('America/Denver');
chdir(__DIR__ . '/..');

echo "# Running composer install for build script\n";
composer_install('bin/builder', false);

chdir('platforms');

echo "# Running composer install for Grav\n";
composer_install('grav/gantry5', true);
composer_install('grav/gantry5/compat', false);

echo "# Running composer install for Joomla\n";
composer_install('joomla/lib_gantry5', true);
composer_install('joomla/plg_system_gantry5_debugbar', false);
composer_install('joomla/lib_gantry5/compat', false);

echo "# Running composer install for WP\n";
composer_install('wordpress/gantry5', true);
composer_install('wordpress/gantry5_debugbar', false);
composer_install('wordpress/gantry5/compat', false);

echo "# Applying compat vendor patches\n";
require __DIR__ . '/apply-compat-patches';

function composer_install($folder, $link)
{
    chdir($folder);
    if ($link && !file_exists('src')) {
        $projectRoot = realpath(__DIR__ . '/..');
        $source = $projectRoot ? $projectRoot . DIRECTORY_SEPARATOR . 'src' : __DIR__ . '/..' . DIRECTORY_SEPARATOR . 'src';
        // Try symlink first
        try {
            @symlink($source, 'src');
        } catch (\Throwable $e) {
            // ignore
        }

        // Fallback: copy directory when symlink is not available (Windows)
        if (!file_exists('src') && $source && is_dir($source)) {
            $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);
            @mkdir('src');
            foreach ($iterator as $item) {
                $dest = 'src' . DIRECTORY_SEPARATOR . ltrim(str_replace($source, '', $item->getPathname()), DIRECTORY_SEPARATOR);
                if ($item->isDir()) {
                    @mkdir($dest);
                } else {
                    copy($item->getPathname(), $dest);
                }
            }
        }
    }
    if (false === exec('composer install --no-dev --no-progress --ignore-platform-req=ext-dom --ignore-platform-req=ext-xml --ignore-platform-req=ext-simplexml --ignore-platform-req=ext-xmlwriter', $output, $result) || $result) {
        echo implode("\n", $output);
        throw new \RuntimeException('Failed to run composer install in ' . $folder);
    }
    chdir(preg_replace('|[^/]+|', '..', $folder));
}
