#! /usr/bin/php
<?php

/**
 * Moodle plugins 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;
$authldapfile = $moodledir . '/auth/ldap/auth.php';
$defaultparamsfile = '/etc/sysconfig/mt-plugins';
$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 "--configfile":
		$configfile = $arg[1];
		unset($argv[$key]);
		break;
	case "--paramsfile":
		$defaultparamsfile = $arg[1];
		unset($argv[$key]);
		break;
	case "--":
		unset($argv[$key]);
		break 2;
	default:
		break;
	}
}

define("CLI_SCRIPT", true);
try {
	require_once($configfile);
	require_once($defaultparamsfile);
} catch (Exception $e) {
	exit(1);
}

foreach ($argv as $key => $value) {
	$arg = preg_split('/=/',$value,2);
	switch ($arg[0]) {
	case "--ldaphosturl":
		$default_plugins_params['auth_plugin_ldap']['host_url'] = $arg[1];
		unset($argv[$key]);
		break;
	case "--ldapcontexts":
		$default_plugins_params['auth_plugin_ldap']['contexts'] = $arg[1];
		unset($argv[$key]);
		break;
	case "--":
		unset($argv[$key]);
		break 2;
	default:
		break;
	}
}

function setconfigparam(&$pluginobj, $paramname, &$paramvalues, $save=true) {
	if (isset($paramvalues[$paramname]))
		try {
			$pluginobj->config->$paramname = $paramvalues[$paramname];
			if ($save)
				set_config($paramname, trim($pluginobj->config->$paramname), $pluginobj->pluginconfig);

			unset($paramvalues[$paramname]);
		} catch (Exception $e) {
			;
		}

}

try {
	require_once($authldapfile);

	foreach ($default_plugins_params as $key1 => &$value1) {
		$thisplugin = new $key1;

		setconfigparam($thisplugin, 'host_url', $value1, false);
		setconfigparam($thisplugin, 'contexts', $value1, false);

		if (isset($thisplugin->config->host_url, $thisplugin->config->contexts)
				&& ! empty($thisplugin->config->host_url)
				&& ! empty($thisplugin->config->contexts)) {
			$thisplugin->process_config($thisplugin->config);

			foreach (array_keys($value1) as $key2) {
				setconfigparam($thisplugin, $key2, $value1);
			}

		}

		unset($thisplugin);
		unset($default_plugins_params[$key1]);
	}

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

exit(1);
?>
