#!/usr/bin/env php
<?php
/**
 * NMS Application Initialization Tool
 *
 * run after Yii initialization.
 *
 */

if (!extension_loaded('openssl')) {
    die('The OpenSSL PHP extension is required by Yii2.');
}

$params = getParams();
$root = str_replace('\\', '/', __DIR__);
$envs = require "$root/environments/index.php";
$envNames = array_keys($envs);
$dbinclude="/etc/nms/debian-db.php";

echo "NMS Application Initialization Tool v1.0\n\n";

$envName = null;
if (empty($params['env']) || $params['env'] === true) {
    echo "Which environment do you want the application to be initialized in?\n\n";
    foreach ($envNames as $i => $name) {
        echo "  [$i] $name\n";
    }
    echo "\n  Your choice [0-" . (count($envs) - 1) . ', or "q" to quit] ';
    $answer = trim(fgets(STDIN));

    if (!ctype_digit($answer) || !in_array($answer, range(0, count($envs) - 1))) {
        echo "\n  Quit initialization.\n";
        exit(0);
    }

    if (isset($envNames[$answer])) {
        $envName = $envNames[$answer];
    }
} else {
    $envName = $params['env'];
}

if (!in_array($envName, $envNames, true)) {
    $envsList = implode(', ', $envNames);
    echo "\n  $envName is not a valid environment. Try one of the following: $envsList. \n";
    exit(2);
}

$env = $envs[$envName];

if (empty($params['env'])) {
    echo "\n  Initialize the application under '{$envNames[$answer]}' environment? [yes|no] ";
    $answer = trim(fgets(STDIN));
    if (strncasecmp($answer, 'y', 1)) {
        echo "\n  Quit initialization.\n";
        exit(0);
    }
}

$rootPath = "$root/environments/{$env['path']}";
if (!is_dir($rootPath)) {
    printError("$rootPath directory does not exist. Check path in $envName environment.");
    exit(3);
}

echo "\n  Start initialization ...\n\n";

$files = getFileList($rootPath);
if (isset($env['skipFiles'])) {
    $skipFiles = $env['skipFiles'];
    array_walk($skipFiles, function(&$value) use($env, $root) { $value = "$root/$value"; });
    $files = array_diff($files, array_intersect_key($env['skipFiles'], array_filter($skipFiles, 'file_exists')));
}

$callbacks = ['setSecretKey', 'initDB', 'uploadPath', 'tempPath'];
foreach ($callbacks as $callback) {
    if (!empty($env[$callback])) {
        $callback($root, $env[$callback]);
    }
}

echo "\n  ... initialization completed.\n\n";

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;
}

function getParams()
{
    $rawParams = [];
    if (isset($_SERVER['argv'])) {
        $rawParams = $_SERVER['argv'];
        array_shift($rawParams);
    }

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

function setSecretKey($root, $paths)
{
    foreach ($paths as $file) {
        echo "   generate secret database key in $file\n";
        $file = $root . '/' . $file;
        $length = 32;
        $bytes = openssl_random_pseudo_bytes($length);
        $key = strtr(substr(base64_encode($bytes), 0, $length), '+/=', '_-.');
        $content = preg_replace('/(("|\')secret("|\')\s*=>\s*)(""|\'\')/', "\\1'$key'", file_get_contents($file));
        file_put_contents($file, $content);
    }
}

function initDB($root, $paths)
{
	global $dbinclude, $params;
    
    if (!empty($params['dbconf'])) {
        $dbinclude=$params['dbconf'];
    }
	
	include_once($dbinclude);
	
    $dbdsn = "mysql:host=localhost;dbname=".$dbname;
	
	foreach ($paths as $file) {
        echo "   replace database settings in $file\n";
		$content = file_get_contents($file);
        $content = preg_replace('/(("|\')dsn("|\')\s*=>\s*)(\'.*;dbname=(.*)\')/', "\\1'$dbdsn'", $content);
		$content = preg_replace('/(("|\')username("|\')\s*=>\s*)(""|\'.*\')/', "\\1'$dbuser'", $content);
		$content = preg_replace('/(("|\')password("|\')\s*=>\s*)(""|\'.*\')/', "\\1'$dbpass'", $content);
		file_put_contents($file, $content);
	}
}

function uploadPath($root, $paths)
{
    foreach ($paths as $file) {
        $uploadPath = $root . DIRECTORY_SEPARATOR . "uploads";
        $content = file_get_contents($file);
        $content = preg_replace('/(("|\')uploadPath("|\')\s*=>\s*)(""|\'\.\.\/\.\.\/uploads\/\')/', "\\1'$uploadPath'", $content);
        file_put_contents($file, $content);
    }
}

function tempPath($root, $paths)
{
    foreach ($paths as $file) {
        $tempPath = $root . DIRECTORY_SEPARATOR . "temp";
        $content = file_get_contents($file);
        $content = preg_replace('/(("|\')tempPath("|\')\s*=>\s*)(""|\'\.\.\/\.\.\/temp\/\')/', "\\1'$tempPath'", $content);
        file_put_contents($file, $content);
    }
}

/**
 * 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";
}
