<?php

$module = 'oc_telegram_shop';

$basePath = dirname(__DIR__) . '/';

if ($basePath === '//') {
    $basePath = '/';
}

$modulesPath = $basePath . 'module/';
$modulePath = $modulesPath . $module . '/upload/';

$files = [];

$iterator = new RecursiveDirectoryIterator($modulePath);
$recursiveIterator = new RecursiveIteratorIterator($iterator);

/** @var SplFileInfo $file */
foreach ($recursiveIterator as $file) {
    if ($file->isFile() && fnmatch($pattern = '*', $file->getFilename())) {
        $files[] = $file->getRealPath();
    }
}

foreach ($files as $file) {
    $link = $basePath . 'web/upload/' . str_replace($modulePath, '', $file);

    if (! is_dir(dirname($link))) {
        if (!mkdir($concurrentDirectory = dirname($link), 0775, true) && !is_dir($concurrentDirectory)) {
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
        }
    }

    echo sprintf('%s => %s', $file, $link) . PHP_EOL;

    @unlink($link);
    symlink($file, $link);
    chmod($link, 0777);
}
