<?php

if (isset($_SERVER['HTTP_HOST'])) {
	header ('Content-type: text/plain; charset=utf-8');
	http_response_code(403);
	die("NO!!!\n");
}

/**************************************************/

$page_type_locations = [
	"page"		=> "pages",
	"post"		=> "posts",
	"gallery"	=> "pages",
];

$page_type_templates = [
	"page"		=> "templates/generic-page.shtml",
	"post"		=> "templates/news-post.shtml",
	"gallery"	=> "templates/image-gallery.shtml",
];

/**************************************************/

if ($argc < 2)
	print_usage_and_exit();

$command = $argv[1];

switch ($command) {
	case "new": {
		if ($argc < 3)
			print_usage_and_exit();
		
		$page_type = $argv[2];
		$page_name = ($argc > 3) ? $argv[3] : ("new-".$page_type);
		
		new_page($page_type, $page_name);
		
		die;				
	}
	default: {
		print_usage_and_exit();
	}
}

/**************************************************/

function new_page($page_type, $page_name) {
	global $page_type_locations, $page_type_templates;
	
	if (!isset($page_type_locations[$page_type]))
		print_error_and_exit("UNSPECIFIED_LOCATION");

	if (!isset($page_type_templates[$page_type]))
		print_error_and_exit("MISSING_TEMPLATE");
	
	$page_directory = "{$page_type_locations[$page_type]}/{$page_name}";
	`mkdir {$page_directory}`;
	`cp {$page_type_templates[$page_type]} {$page_directory}/index.shtml`;
	echo "Created new {$page_type} at {$page_directory}/index.shtml.\n";
}

function print_usage_and_exit() {
	global $page_type_templates;

	echo "Usage is:\n";
	echo "    deus.php <command> [ <options> ]\n";
	echo "\n";
	echo "Available commands are:\n";
	echo "    new        Create a new page of the specified type and name\n";
	echo "               Options:\n";
	echo "                   Page type (" . implode(", ", array_keys($page_type_templates)) . ") and optional page name\n";
	echo "               Examples:\n";
	echo "                   deus.php new post\n";
	echo "                       (Creates new generic post called 'new-post')\n";
	echo "                   deus.php new gallery my-cool-gallery\n";
	die;
}

function print_error_and_exit($error_code) {
	switch ($error_code) {
		case "UNSPECIFIED_LOCATION": {
			echo "Target location not specified for pages of the specified type.\n";
			break;
		}
		case "MISSING_TEMPLATE": {
			echo "No template provided for pages of the specified type.\n";
			break;
		}
		default: {
			echo "NO!!!\n";
			break;
		}
	}
	die;
}

?>