<?php

	//
	//  Install Seme4 Platform
	//  Copyright 2014 Seme4 Ltd. All rights reserved.
	//

	set_time_limit(0);

	print "<h2>Installing the Seme4 Platform...</h2>";
	flush();
	
	//  check directory is writable
	if (!is_writable('./')) die("<p><strong>Error</strong>: the current directory <tt>" . realpath(dirname(__FILE__)) . "</tt> must be writable by the web server</p>");

	//  installation consists of the following steps/commands
	$commands = array(

		'Retrieving code from SVN repository' 		
		=> 'svn co --no-auth-cache --username install --password readonly http://svn.seme4.com/platform/trunk/ --force ./',

		'Acquiring and unpacking required libraries'	
		=> 'cd lib ; make',
	);

	//  execute each step in turn. if there is a problem, abort.
	foreach($commands as $s => $c) {
		$op = array();
		print "<h3>$s...</h3>\n";
		flush();
		exec("$c 2>&1", $op, $retVal);
		if ($retVal != 0) {
			print "<pre style='background: #eee; border: 1px solid #ddd; margin: 1em; padding: 1em;'>";
			print join("\n", $op);
			print "</pre>\n";
			die("<p><strong>Error</strong>: command did not return exit value <tt>0</tt></p>\n\n\n");
		} else {
			print "<p style='text-indent: 2em;'><i>successful</i></p>\n";
		}
		flush();
	}

	//  ensure we have config file
	if (!file_exists('config.ttl')) {
		copy('config.ttl.dist', 'config.ttl');
		chmod('config.ttl', 0666);	//  this is bad, as passwords globally visible, but useful to allow easy editing
	}

	//  ok :)
	print "<h3>Success!</h3>\n";
	print "<p>The Seme4 Platform <a href=\"./\">should now be ready!</a></p>";
	print "<p>Ensure you customise <tt>config.ttl</tt> as appropriate</p>";


	//  write uninstall.sh
	//  TODO -- this is a static list, which will need to be maintained
	file_put_contents('uninstall.sh', "#!/bin/sh\n\n# Completely remove Seme4 Platform from filesystem\n\nsudo rm -rf .svn .htaccess assets auth.htpasswd config.ttl.dist config.ttl filestore index.php install.php lib logs RAGLD.php scripts services templates uninstall.sh");
