#!/usr/bin/php
<?php

echo "Moments project creation wizard\n";
echo "-------------------------------\n";
$namespace = '\\' . readline('Desired namespace (e.g. \ACME\Website): \\');

$from = __DIR__;
if ($from[-1] != '/') {
	$from .= '/';
}
$from .= '../project-template/';

$to = getcwd();
if ($to[-1] != '/') {
	$to .= '/';
}

if (file_exists($to . 'public')) {
	echo "There's already a public directory, preventing initialisation.";
	return;
}

$replacements = [
	['__NAMESPACE__', $namespace],
	['__NAMESPACE_REL__', substr($namespace, 1)],
	['__NAMESPACE_ESCAPED__', str_replace('\\', '\\\\', $namespace)],
];

function copyDir($src, $dst)
{
	global $namespace;
	
	$d = dir($src);
	while ($e = $d->read()) {
		if ($e[0] == '.') {
			continue;
		}
		$er = replaceStuff($e);
		if (is_dir($src . $e)) {
			if ($e == '_src_') {
				// Expand namespace to directory
				$ns = explode('\\', substr($namespace, 1));
				$ndst = $dst . 'src/';
				mkdir($ndst);
				foreach ($ns as $p) {
					$ndst .= $p . '/';
					if (!file_exists($ndst)) {
						mkdir($ndst);
					}
				}
				copyDir($src . $e . '/', $ndst);
			} else {
				mkdir($dst . $er);
				copyDir($src . $e . '/', $dst . $er . '/');
			}
		} else {
			$f = file_get_contents($src . $e);
			$f = replaceStuff($f);
			file_put_contents($dst . $er, $f);
		}
	}
}

function replaceStuff($f)
{
	global $replacements;
	
	foreach ($replacements as $r) {
		$f = str_replace($r[0], $r[1], $f);
	}
	
	return $f;
}

// Copying files from template
copyDir($from, $to);

// Adding autoloading for created namespace
$composer = json_decode(file_get_contents($to . 'composer.json'), true);

if (!isset($composer['autoload'])) {
	$composer['autoload'] = [];
}
if (!isset($composer['autoload']['psr-4'])) {
	$composer['autoload']['psr-4'] = [];
}
$composer['autoload']['psr-4'][substr($namespace, 1) . '\\'] = 'src' . str_replace('\\', '/', $namespace);

// Adding preparation script
if (!isset($composer['scripts'])) {
	$composer['scripts'] = [];
}
if (!isset($composer['scripts']['post-update-cmd'])) {
	$composer['scripts']['post-update-cmd'] = [];
}
$composer['scripts']['post-update-cmd'][] = 'vendor/bin/prepare-moments';
$composer['scripts']['post-install-cmd'][] = 'vendor/bin/prepare-moments';

file_put_contents($to . 'composer.json', json_encode($composer, JSON_PRETTY_PRINT));

// Adjusting config
$config = json_decode(file_get_contents($to . 'config/config.json'), true);
$config['secret'] = base_convert(bin2hex(random_bytes(64)), 16, 36);
file_put_contents($to . 'config/config.json', json_encode($config, JSON_PRETTY_PRINT));

// Done
echo "
Done initialisation.

Next steps on your to-do list:
 - run something like: composer dump-autoload
 - Have fun and implement, start with setting up the routes
   in config/config.json
";