#!/usr/bin/php
<?php

require_once("/usr/share/ombutel/www/includes/cli.php");

use ombutel\apache;

function print_usage() {
	global $argv, $component_map;
	echo "Usage {$argv[0]} [-https on|off] [-redirect-http on|off] [-key <encoded>] [-cert <encoded>] [-chain <encoded>]\n";
	echo "  -https           Toggle HTTPS support.\n";
	echo "  -redirect-http   Force HTTP requests to HTTPS.\n";
	echo "  -key             Private key, gzipped and base64-encoded.\n";
	echo "  -cert            Certificate, gzipped and base64-encoded.\n";
	echo "  -chain           Chain certificate, gzipped and base64-encoded.\n";
	echo "\n";
	exit(1);
}

function parse_args() {
	global $argc, $argv;
	$params = (object) [];
	$args = array_slice($argv, 1);
	while ($args) {
		switch($arg = array_shift($args)) {
			case "-https": {
				if (!$args) {
					return print_usage();
				}
				$params->https = array_shift($args) == "on";
				break;
			}
			case "-redirect-http": {
				if (!$args) {
					return print_usage();
				}
				$params->redirect_http = array_shift($args) == "on";
				break;
			}
			case "-key": {
				if (!$args) {
					return print_usage();
				}
				$params->private_key = array_shift($args);
				break;
			}
			case "-cert": {
				if (!$args) {
					return print_usage();
				}
				$params->certificate = array_shift($args);
				break;
			}
			case "-chain": {
				if (!$args) {
					return print_usage();
				}
				$params->chain_certificate = array_shift($args);
				break;
			}
			case "--help":
			case "-?":
			case "-h": {
				print_usage();
			}
		}
	}
	return $params;
}

$params = parse_args();

try {
	apache::configure($params);
} catch (Exception $e) {
	$reason = $e->getMessage();
	$trace = $e->getTraceAsString();
	fprintf(STDERR, "Could not configure Apache:\n%s\n%s\n", $reason, $trace);
	exit(1);
}
