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

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

use MAKS\Velox\Backend\Config;
use MAKS\Velox\Frontend\Path;


if (!Config::get('cli.app-mirror.enabled', false)) {
    echo 'Command is disabled!', PHP_EOL;
    exit(1);
}


$fileSystem = new class {
    public function link(string $target, string $link): bool
    {
        if (is_link($link)) {
            if (is_dir($link) && PHP_OS == 'WINNT') {
                rmdir($link);
            } else {
                unlink($link);
            }
        }

        if (!file_exists(dirname($link))) {
            mkdir(dirname($link), 0755, true);
        }

        return symlink($target, $link);
    }

    public function delete(string $path): bool
    {
        if (is_link($path)) {
            unlink($path);
        }

        if (is_dir($path)) {
            $files = scandir($path);
            foreach ($files as $file) {
                if ($file !== '.' && $file !== '..') {
                    $this->delete($path . '/' . $file);
                }
            }

            return rmdir($path);
        }

        if (file_exists($path)) {
            return unlink($path);
        }

        return false;
    }

    public function copy(string $source, string $destination): bool
    {
        if (file_exists($destination)) {
            $this->delete($destination);
        }

        if (is_dir($source)) {
            mkdir($destination, 755, true);
            $files = scandir($source);
            foreach ($files as $file) {
                if ($file !== '.' && $file !== '..') {
                    $this->copy($source . '/' . $file, $destination . '/' . $file);
                }
            }

            return true;
        }

        if (file_exists($source)) {
            return copy($source, $destination);
        }

        return false;
    }

    public function getValidName($name, string $original): string
    {
        return !is_int($name)
            ? Path::resolve('/public/' . (string)$name)
            : str_replace(
                Config::get('global.paths.root'),
                Config::get('global.paths.public'),
                $original
            );
    }
};


$link = Config::get('cli.app-mirror.args.link', []);
$copy = Config::get('cli.app-mirror.args.copy', []);


foreach ($link as $name => $target) {
    $fileSystem->link(
        $target,
        $fileSystem->getValidName($name, $target)
    );
}

foreach ($copy as $name => $source) {
    $fileSystem->copy(
        $source,
        $fileSystem->getValidName($name, $source)
    );
}


echo 'OK!', PHP_EOL;
exit(0);
