#! /usr/bin/php
<?php

/**
 * Moodle tools
 *
 * @package   mt
 * @copyright 2012 Aleksey Avdeev <solo@altlinux.ru>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later
 */

if ($argc < 1) {
	exit(1);
}

$moodledir = '/var/www/webapps/moodle';
$configfilename = 'config.php';
$configfile = $moodledir . '/' . $configfilename;
$format = "%s\n";
$username = null;
$password = null;
$passwordhash = null;
$user = null;

$progname = array_shift($argv);

foreach ($argv as $key => $value) {
	$arg = preg_split('/=/',$value,2);
	switch ($arg[0]) {
	case "--user":
		$username = $arg[1];
		unset($argv[$key]);
		break;
	case "--password":
		$password = $arg[1];
		unset($argv[$key]);
		break;
	case "--passwordhash":
		$passwordhash = $arg[1];
		unset($argv[$key]);
		break;
	case "--file":
		$configfile = $arg[1];
		unset($argv[$key]);
		break;
	case "--format":
		$format = $arg[1] . "\n";
		unset($argv[$key]);
		break;
	case "--":
		unset($argv[$key]);
		break 2;
	default:
		break;
	}
}

$name = array_shift($argv);

define("CLI_SCRIPT", true);
try {
	require_once($configfile);

	if (is_null($passwordhash) and ! is_null($password))
		$passwordhash = hash_internal_user_password($password);

	$DB->set_field('user', 'password', $passwordhash, array('mnethostid'=>$CFG->mnet_localhost_id, 'username'=>$username, 'auth'=>'manual'));

	exit(0);
} catch (Exception $e) {
	;
}

exit(1);
?>
