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

use Clify\Cli;

// FIXME: нужен тотальный рефактор этого файла

$autoload = __DIR__ . '/../vendor/autoload.php';
require file_exists($autoload) ? $autoload : __DIR__ . '/../../../autoload.php';

$cli = new Cli;

$cli->out("{cyan}+--------------------------+{reset}
{cyan}| {white}PHP Telegram Bot API CLI{cyan} |
+--------------------------+{reset}" . PHP_EOL);

$basepath = __DIR__ . '/../';

$args = $cli->getArgs();

/**
 * -h --help
 */
if (array_key_exists('h', $args) || array_key_exists('help', $args)) {
    $cli->out("{white}Available commands:{reset}\n
    {light_cyan}--init <save_path>{reset}    - Create a Bot skeleton project structure (e.g. {white}\"vendor/bin/bot --init ./\"{reset});
    {light_cyan}--config <save_path>{reset}  - Create a Bot configuration file. (e.g. {white}\"vendor/bin/bot --config ./\"{reset});

    {light_cyan}-h, --help{reset}            - List of available commands;{reset}" . PHP_EOL);
}

/**
 * --init <path>
 */
if (isset($args['init'])) { 
    $path = realpath($args['init']);

    if (!file_exists($path)) {
        $cli->out("{red}Error: Init path not exists." . PHP_EOL);
        die;
    }

    dir_copy($basepath . 'examples/skeleton', $path);
    $cli->out('{green}✅ Project skeleton successfully created!' . PHP_EOL);
    $cli->out('{light_cyan}💡 Please, install dependencies: {yellow}composer install{reset}' . PHP_EOL);
}

/**
 * --config <path>
 */
if (isset($args['config'])) {
    $path = realpath($args['config']);

    if (!file_exists($path)) {
        $cli->out("{light_red}Error: Config path not exists." . PHP_EOL);
        die;
    }

    copy($basepath . 'examples/config.example.php', rtrim($path, '\/') . '/bot.config.php');
    $cli->out('{green}✅ Config file `bot.config.php` successfully created!' . PHP_EOL);
}

function dir_copy($src, $dst)
{
    $dir = opendir($src);

    @mkdir($dst);

    while ($file = readdir($dir)) {
        if (($file != '.') && ($file != '..')) {
            if (is_dir($src . '/' . $file)) {
                dir_copy($src . '/' . $file, $dst . '/' . $file);
            } else {
                copy($src . '/' . $file, $dst . '/' . $file);
            }
        }
    }

    closedir($dir);
}
