<?php

$BASE = dirname(dirname(__FILE__));
set_include_path(get_include_path()
                 .PATH_SEPARATOR. "$BASE/src/lib"
                 .PATH_SEPARATOR. "$BASE/src/ext"
                 );
$uri = $_SERVER['REQUEST_URI'];

require_once('include.php');

$conf_file = "$BASE/conf.php";
if (!mm_isSqlConfigured($conf_file)) {
	require_once('Template.class.php');
	$t = new Template($BASE);
	
	$t->header('Message Manager: Installer');

	$t->paragraph("First we need to set up the SQL configuration, ".
	              "then we will set up the first user.");
	
	$t->openTag('form', array('method'=>'post','action'=>$uri));
	$t->tag('input', array('type'=>'hidden', 'name'=>'try', 'value'=>'t'));
	$try = isset($_POST['try']);
	
	$mysql = false;
	if ($try) {
		@$mysql = mysql_connect($_POST['db_host'],
		                        $_POST['db_user'],
		                        $_POST['db_password']);
	}
	
	////////////////////////////////////////////////////////////////////////
	
	$t->openFieldset("MySQL Authentication", $mysql);
	$t->inputText('db_host', 'Hostname', '',
	              getParam('db_host','localhost'), $mysql);
	$t->inputText('db_user', 'Username', '',
	              getParam('db_user'), $mysql);
	$t->inputPassword('db_password', 'Password', '',
	                  getParam('db_password'), $mysql);
	if ($try && !$mysql) {
		$t->inputP("Could not authenticate: ".mysql_error(), true);
	}
	$t->closeFieldset();
	
	////////////////////////////////////////////////////////////////////////
	
	$charset = false;
	if ($mysql) {
		$charset = mysql_set_charset($_POST['db_charset'], $mysql);
		if (!$charset) {
			$charset_error = mysql_error($mysql);
		}
	}
	
	$db = false;
	$db_message = '';
	if ($charset) {
		$t->setRet(true);
		$db = mm_mysql_db($mysql, $_POST['db_name'], $db_message);
		$t->setRet(false);
	}
	
	$db_prefix = $_POST['db_prefix'];
	
	$table = false;
	if ($db) {
		$table_exists = mm_mysql_table_exists($mysql,$db_prefix.'auth');
		if (!$table_exists) {
			$query =
				'CREATE TABLE '.$db_prefix."auth (\n".
				"  uid INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n".
				"  name VARCHAR(255),\n".
				"  hash CHAR(60)\n".
				"  status INT\n"
				");";
			$table = mysql_query($query);
			if (!$table) {
				$table_error = mysql_error($mysql);
			}
		} else {
			$table = true;
		}
	}
	
	////////////////////////////////////////////////////////////////////////
	
	$t->openFieldset("MySQL Settings", $table);
	
	$t->inputText('db_charset', 'Charset',
	              "I've heard that you may need to change this if ".
	              "you use an old version of MySQL. 'utf8' is ".
	              "generally a good option, though.",
	              getParam('db_charset','utf8'), $table);
	if ($mysql) {
		$str = $_POST['db_charset'];
		if ($charset) {
			$t->inputP("Set charset to <q>$str</q>.");
		} else {
			$t->inputP("Could not set charset to ".
			           "<q>$str</q>: ".$charset_error, true);
		}
	}
	
	$t->inputText('db_name', 'Database name', '',
	              getParam('db_name', 'messagemanager'), $table);
	echo $db_message;
	
	$t->inputText('db_prefix', 'Table prefix',
	              'Just use simple characters, like [A-Za-z0-9_], '.
	              'and keep it short.',
	              getParam('db_prefix','mm_'), $table);
	
	if ($db) {
		$db_name = '<q>'.$db_prefix.'auth</q>';
		if ($table) {
			if ($table_exists) {
				$msg="Table $db_name already exists.";
			} else {
				$msg="Created table $db_name.";
			}
		} else {
			$msg="Could not create table $db_name: ".$table_error;
		}
		$t->inputP($msg, !$table);
	}
	
	$t->closeFieldset();
	
	////////////////////////////////////////////////////////////////////////
	
	$fh = false;
	if ($table) {
		$fh = fopen('conf.php', 'w');
		if ($fh === FALSE) {
			$msg="Could not open file <q>conf.php</q> for writing.";
			$template->paragraph($msg, true);
		} else { 
			fwrite($fh, '<?php global $db_config;'."\n");
			fwrite($fh, configStr('host'));
			fwrite($fh, configStr('user'));
			fwrite($fh, configStr('password'));
			fwrite($fh, "\n");
			fwrite($fh, configStr('charset'));
			fwrite($fh, configStr('name'));
			fwrite($fh, configStr('prefix'));
			fclose($fh);
		}
	}
	if ($fh) {
		$t->closeTag('form');
		$t->openTag('form', array('action'=>$uri));
		$t->tag('input', array('type'=>'submit',
		                       'value'=>'Cool beans, go to step 2!'));
	} else {
		$t->tag('input', array('type'=>'submit', 'value'=>'Submit'));
	}
	$t->closeTag('form');
	$t->footer();
	////////////////////////////////////////////////////////////////////////
} else {
	require_once('MessageManager.class.php');
	$m = new MessageManager($conf_file);
	$t = $m->template();
	
	$t->header('Message Manager: Installer');
	
	$user_count = $m->countUsers();
	
	if ($user_count<1) {
		$t->openTag('form', array('method'=>'post', 'action'=>$uri));
		$t->tag('input', array('type'=>'hidden',
		                       'id'=>'try',
		                       'name'=>'try',
		                       'value'=>'t'));
		$try = isset($_POST['try']);
		
		$pw = false;
		if ($try) {
			$pw = ( $_POST['mm_password'] ===
			        $_POST['mm_password_verify'] );
		}
		
		$admin = false;
		if ($pw) {
			$user = $_POST['mm_user'];
			$password = $_POST['mm_password'];
			
			$uid = $m->addUser($user, $password);
			$admin = $m->setStatus($uid, 2);
			if (!$admin) {
				$admin_error = mysql_error($mysql);
			}
		}
		
		////////////////////////////////////////////////////////////////
		
		$t->openFieldset("First Account (administrator)",$admin);
		$t->inputText('mm_user', 'Username',
		              "Must be <= 255 characters.",
		              getParam('mm_user','root'), $admin);
		$t->inputNewPassword('mm_password', 'Password',
		                     ($pw?getParam('mm_password'):''),
		                     $admin);
		if ($try && !$pw) {
			$msg="Passwords don't match.";
			$template->inputP($msg, true);
		}
		if ($pw) {
			$user = "<q>".$_POST['mm_user'].'</q>';
			if ($admin) {
				$msg="Created user $user.";
			} else {
				$msg="Could not create user $user: ".
					$admin_error;
			}
			$t->inputP($msg, !$admin);
		}
		$t->closeFieldset();
		
		////////////////////////////////////////////////////////////////
		
		if (!$admin) {
			$t->tag('input', array('type'=>'submit',
			                       'value'=>'Submit'));
		}
		$t->closeTag('form');
	} else {
		$t->paragraph("File conf.php already exists, and there ".
		                     "is at least one user. Return to the ".
		                     "<a href='index.php'>main page</a>.");
	}
	$t->footer();
}