#!/usr/bin/env php
<?php
/**
 * kcbasic初始化工具
 */
echo "KcDev Initialization Tool v1.0\n\n";

/* 检查openssl模块是否已经安装并正确加载 */
if (!extension_loaded('openssl')) {
    die('The OpenSSL PHP extension is required by Yii2.');
}

$params = getParams();
$root = str_replace('\\', '/', __DIR__);
$skeletonPath = "environments/skeleton";

/* 初始化基础骨架 */
echo "\nDo you want to init the skeleton? [Yes|No]\n";
$answer = trim(fgets(STDIN));
if ($answer == 'yes') {
    echo "\n  Skeleton initialization ...\n\n";
    $files = getFileList($skeletonPath);
    foreach ($files as $file) {
        $all = false;
        if (!copyFile($root, "$skeletonPath/$file", $file, $all, $params)) {
            break;
        }
    }
    echo "\n  ... skeleton initialization completed.\n\n";
    exit;
}


/* 输入app名称 */
echo "Please enter the app name:";
$appName = trim(strtolower(fgets(STDIN)));

if (!preg_match('/^[_a-z]{3,12}$/i', $appName)) {
    printError("App name must be 3 to 12 letters or underline");
    exit();
}


if (is_dir($root . '/' . $appName)) {
    printError("App {$appName} is exists");
    exit();
}

/* 输入app类型 */
$types = ["web application", "wechat application", "restfull api"];
echo "\n\nPlease select the type of your app.\n";
foreach ($type as $i => $name) {
    echo "  [$i] $name\n";
}
echo "\n  Your choice [0-" . (count($types) - 1) . ', or "q" to quit] ';
$answer = trim(fgets(STDIN));

if (!ctype_digit($answer) || !in_array($answer, range(0, count($types) - 1))) {
    printError("Please enter the correct nunmber");
    exit();
}
$type = $answer;

//TODO 后面希望通过这个脚本 可以创建web后台 H5前台 API等程序的基础模板,这些模板保存在environment目录里面

/**
 * Prints error message.
 * @param string $message message
 */
function printError($message) {
    echo "\n  " . formatMessage("Error. $message", ['fg-red']) . " \n";
}

/**
 * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
 *
 * - windows without ansicon
 * - not tty consoles
 *
 * @return boolean true if the stream supports ANSI colors, otherwise false.
 */
function ansiColorsSupported() {
    return DIRECTORY_SEPARATOR === '\\' ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON' : function_exists('posix_isatty') && @posix_isatty(STDOUT);
}

/**
 * Get ANSI code of style.
 * @param string $name style name
 * @return integer ANSI code of style.
 */
function getStyleCode($name) {
    $styles = [
        'bold' => 1,
        'fg-black' => 30,
        'fg-red' => 31,
        'fg-green' => 32,
        'fg-yellow' => 33,
        'fg-blue' => 34,
        'fg-magenta' => 35,
        'fg-cyan' => 36,
        'fg-white' => 37,
        'bg-black' => 40,
        'bg-red' => 41,
        'bg-green' => 42,
        'bg-yellow' => 43,
        'bg-blue' => 44,
        'bg-magenta' => 45,
        'bg-cyan' => 46,
        'bg-white' => 47,
    ];
    return $styles[$name];
}

/**
 * Formats message using styles if STDOUT supports it.
 * @param string $message message
 * @param string[] $styles styles
 * @return string formatted message.
 */
function formatMessage($message, $styles) {
    if (empty($styles) || !ansiColorsSupported()) {
        return $message;
    }

    return sprintf("\x1b[%sm", implode(';', array_map('getStyleCode', $styles))) . $message . "\x1b[0m";
}

/**
 * 获取给定目录底下的所有文件
 * @param string $root
 * @param string $basePath
 * @return array
 */
function getFileList($root, $basePath = '') {
    $files = [];
    $handle = opendir($root);
    while (($path = readdir($handle)) !== false) {
        if ($path === '.git' || $path === '.svn' || $path === '.' || $path === '..') {
            continue;
        }
        $fullPath = "$root/$path";
        $relativePath = $basePath === '' ? $path : "$basePath/$path";
        if (is_dir($fullPath)) {
            $files = array_merge($files, getFileList($fullPath, $relativePath));
        } else {
            $files[] = $relativePath;
        }
    }
    closedir($handle);
    return $files;
}

/**
 * 文件复制
 * @param string $root
 * @param string $source
 * @param string $target
 * @param boolean $all
 * @param array $params
 * @return boolean
 */
function copyFile($root, $source, $target, &$all, $params) {
    if (!is_file($root . '/' . $source)) {
        echo "       skip $target ($source not exist)\n";
        return true;
    }
    if (is_file($root . '/' . $target)) {
        if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target)) {
            echo "  unchanged $target\n";
            return true;
        }
        if ($all) {
            echo "  overwrite $target\n";
        } else {
            echo "      exist $target\n";
            echo "            ...overwrite? [Yes|No|All|Quit] ";


            $answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN));
            if (!strncasecmp($answer, 'q', 1)) {
                return false;
            } else {
                if (!strncasecmp($answer, 'y', 1)) {
                    echo "  overwrite $target\n";
                } else {
                    if (!strncasecmp($answer, 'a', 1)) {
                        echo "  overwrite $target\n";
                        $all = true;
                    } else {
                        echo "       skip $target\n";
                        return true;
                    }
                }
            }
        }
        file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
        return true;
    }
    echo "   generate $target\n";
    @mkdir(dirname($root . '/' . $target), 0777, true);
    file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
    return true;
}

/**
 * 获取输出参数
 * @return array
 */
function getParams() {
    $rawParams = [];
    if (isset($_SERVER['argv'])) {
        $rawParams = $_SERVER['argv'];
        array_shift($rawParams);
    }

    $params = [];
    foreach ($rawParams as $param) {
        if (preg_match('/^--(\w+)(=(.*))?$/', $param, $matches)) {
            $name = $matches[1];
            $params[$name] = isset($matches[3]) ? $matches[3] : true;
        } else {
            $params[] = $param;
        }
    }
    return $params;
}
?>