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

if (!file_exists(__DIR__.'/vendor/autoload.php')) {
    echo "Run `composer install` before you run the `link` script.\n";
    exit(1);
}

require __DIR__.'/vendor/autoload.php';

use Symfony\Component\Filesystem\Filesystem;

/**
 * Links dependencies to components to a local clone of the main web-auth/webauthn-framework GitHub repository.
 * Inspired by symfony/symfony and async-aws/aws
 */

$copy = false !== $k = array_search('--copy', $argv, true);
$copy && array_splice($argv, $k, 1);
$pathToProject = $argv[1] ?? getcwd();

if (!is_dir("$pathToProject/vendor/web-auth")) {
    echo 'Link (or copy) dependencies to components to a local clone of the main web-auth/webauthn-framework GitHub repository.'.PHP_EOL.PHP_EOL;
    echo "Usage: $argv[0] /path/to/the/project".PHP_EOL;
    echo '       Use `--copy` to copy dependencies instead of symlink'.PHP_EOL.PHP_EOL;
    echo "The directory \"$pathToProject\" does not exist or the dependencies are not installed, did you forget to run \"composer install\" in your project?".PHP_EOL;
    exit(1);
}

$packages = [];

$filesystem = new Filesystem();
$directories = glob(__DIR__.'/src/*', GLOB_ONLYDIR | GLOB_NOSORT);

foreach ($directories as $dir) {
    if ($filesystem->exists($composer = "$dir/composer.json")) {
        $packages[json_decode(file_get_contents($composer))->name] = $dir;
    }
}

if (is_dir("$pathToProject/vendor/web-auth/webauthn-framework")) {
    if ($filesystem->exists($composer = "$pathToProject/vendor/web-auth/webauthn-framework/composer.json")) {
        $packages[json_decode(file_get_contents($composer))->name] = realpath(__DIR__);
    }
}

foreach (glob("$pathToProject/vendor/web-auth/*", GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
    $package = 'web-auth/'.basename($dir);
    if (!$copy && is_link($dir)) {
        echo "\"$package\" is already a symlink, skipping.".PHP_EOL;
        continue;
    }

    if (!isset($packages[$package])) {
        continue;
    }

    $packageDir = ('\\' === DIRECTORY_SEPARATOR || $copy) ? $packages[$package] : $filesystem->makePathRelative($packages[$package], dirname(realpath($dir)));
    $filesystem->remove($dir);

    if ($copy) {
        $filesystem->mirror($packageDir, $dir);
        echo "\"$package\" has been copied from \"$packages[$package]\".".PHP_EOL;
    } else {
        $filesystem->symlink(rtrim($packageDir, '/'), $dir);
        echo "\"$package\" has been linked to \"$packages[$package]\".".PHP_EOL;
    }
}
