<?php
$MODULE="pmsi";
$TITLE="Benchmark Groupe PMSI";
$DFTENDSTATUS="OK";
$ARGS="-raz";
/** Laisser les lignes 2 à 5 sans changer la casse et sans espaces et dans cet ordre
 * car le script est lu et analysé quand il est exécuté via .exe ou Jenkins
 * pour gestion des fichiers .pid dans system\batch\logs
 */

/** Le dossier de l'environnement est le dossier parent du dossier 'modules' */
list($environmentPath) = explode(DIRECTORY_SEPARATOR.'modules', dirname(__FILE__));
$environmentPath .= DIRECTORY_SEPARATOR;

require_once $environmentPath . 'modules/base/php/lib/cti/Batch/iCTI_batch_common.php';
require_once $environmentPath . 'modules/base/php/classSimpleXML.php';
require_once $environmentPath . 'modules/outils/php/httpService_cacheManager_cleanCache.php';
require_once $environmentPath . 'modules/base/php/lib/cti/Database/Database2Factory.class.php';
require_once $environmentPath . 'modules/base/php/lib/cti/Environnement/Environnement.class.php';
require_once $environmentPath . 'modules/base/php/lib/cti/EnvironmentSettings/EnvironmentDatabaseSettings.php';

global $ENDSTATUS;
global $iCTI_connexion;
global $cti_args;
global $ADMPROVIDER;
global $ADMPROVIDER2;
global $ADMPROVIDER_PREFIX;
global $ADMPROVIDER2_PREFIX;
global $ENV_TYPEETS;
global $ENV_ADM_ANNEEDEBUT;
global $nbE;

logStartMsg();

// Arguments transmis ?
$cti_args = new CTI_Args_class();
$cti_args->checkArgs();

if (iCTI_connect()) {

	// création du répertoire utilisé par la fonction base.cti_copy_table(i_fromdblink text, i_fromtable text, i_totable text)
	if (!is_dir('C:/TEMP')) {
		mkdir('C:/TEMP');
	}
	
	exec_environnements();

	logInfoMsg("Nettoyage cache");
	cleanAllCache("iCTI_pmsi", TRUE);
		
}

iCTI_disconnect();

logEndMsg();


// récupération historique
function exec_environnements() {

	global $iCTI_connexion;
	global $iCTI_dbname;
	global $iCTI_rmtip;
	global $iCTI_port;

	global $environments_array;

	global $cti_args;


	// Chargement requetes SQL
	$environmentVars=array();
	

	$sqlOptions=array();
	
	if (! isset($cti_args->args["-moisforces"])) {
		$cti_args->args["-moisforces"] = "0";
	}
		
	$cti_sqlStatements = new CTI_SqlStatements_class("iCTI_BenchmarkGroupe.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
	$cti_sqlStatements->executeStatementsNode("INIT");
	
	$dbInfo = Environnement::getInstance()->getDbInfo();
	
	foreach ($environments_array as $environment_array) {
		
		$environmentVars["DBNAME_CONSO"] = $dbInfo['dbname'];
		$environmentVars["DBPORT_CONSO"] = $dbInfo['port'];
		$environmentVars["DBHOST_CONSO"] = $iCTI_rmtip;
		
		$environmentVars["DBNAME"] = $environment_array["dbname"];
		$environmentVars["DBPORT"] = $environment_array["dbport"];
		$environmentVars["DBHOST"] = $environment_array["dbhost"];
        $environmentVars["DBUSERNAME"] = $environment_array["dbusername"];
        $environmentVars["DBPASSWORD"] = $environment_array["dbpassword"];
		if ($environmentVars["DBHOST"] ==  "localhost") {
			$environmentVars["DBHOST_CONSO"] = $environmentVars["DBHOST"];
		}
		$environmentVars["FINESS"] = $environment_array["finess"];
		$environmentVars["FINESS_TEXTE"] = $environment_array["texte"];

		$cti_sqlStatements_finess = new CTI_SqlStatements_class("iCTI_BenchmarkGroupe.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
		$cti_sqlStatements_finess->executeStatementsNode("EXECENV");
	}
		
	$cti_sqlStatements->executeStatementsNode("POST");
	
	

	

}



function iCTI_connect() {


global $iCTI_connexion;
global $iCTI_cache;

global $iCTI_dbname;
global $iCTI_rmtip;
global $iCTI_port;

global $environments_array;



	$iCTI_connexion = FALSE;

	$file = "../../../settings/settings.XML";
	$settings_xml = simplexml_load_file($file);
	
	$ENV_CONSOLIDATION = "0";
	$iCTI_rmtip = "";

	foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if ($propertyNode['name'] == 'CONSOLIDATION') {
				$ENV_CONSOLIDATION = $propertyNode['value'];
			}
			if ($propertyNode['name'] == 'OPTSYSTEM_REMOTE_IP') {
				$iCTI_rmtip = $propertyNode['value'];
			}
		}
	}
	
	
	if ($ENV_CONSOLIDATION != "1") {
		logErrorMsg("Environnement NON CONSOLIDE");
		return FALSE;
	}
	
	
	$environment_error = FALSE;
	$environments_array = array();
	foreach ($settings_xml->CONSOLIDATION as $consolidationNode) {
		foreach ($consolidationNode->ENVIRONMENT as $environmentNode) {

			$environment_dir = "";
			$environment_finess = "";
			$environment_texte = "";
			$environment_dbname = "";

			foreach ($environmentNode->PROPERTY as $propertyNode) {
				if ($propertyNode['name'] == 'ENVIRONMENT') {
					$environment_texte = utf8_decode($propertyNode['value']);
				}
				if ($propertyNode['name'] == 'DIR') {
					$environment_dir = $propertyNode['value'];
				}
			}

            $dbSettings = new EnvironmentDatabaseSettings($environment_dir);
            try {
                $dbSettings->readSettings();
            } catch (Exception $e) {
                logErrorMsg($e->getMessage());
                $environment_error = TRUE;
            }

            $environment_host = $dbSettings->getHost();
            $environment_port = $dbSettings->getPort();
            $environment_dbname = $dbSettings->getName();
            $environment_username = $dbSettings->getUsername();
            $environment_password = $dbSettings->getPassword();
			
			if (file_exists($environment_dir . "/settings/settings.xml")) {
				$environment_settings_xml = simplexml_load_file($environment_dir . "/settings/settings.xml");
				if ($environment_settings_xml) {
					foreach ($environment_settings_xml->ENVIRONMENT as $toEnvironmentNode) {
						foreach ($toEnvironmentNode->PROPERTY as $toPropertyNode) {
							if ($toPropertyNode['name'] == 'FINESS') {
								$environment_finess = $toPropertyNode['value'];
							}
							if ($toPropertyNode['name'] == 'ENVIRONMENT') {
								$environment_texte = utf8_decode($toPropertyNode['value']);
							}
						}
					}
				}
			}
			else {
				logErrorMsg("Environnement $environment_texte sur $environment_dir inexistant ou mal configuré");
				$environment_error = TRUE;
			}
			
			if ($environment_dbname == "") {
				logErrorMsg("Environnement $environment_texte sur $environment_dir inexistant ou mal configuré");
				$environment_error = TRUE;
			}
			else {
				if ($environment_finess == "") {
					logErrorMsg("Environnement $environment_texte sur $environment_dir inexistant ou mal configuré");
					$environment_error = TRUE;
				}
				else {
					$environment_array = array();
					$environment_array["dir"] = $environment_dir;
					$environment_array["finess"] = $environment_finess;
					$environment_array["texte"] = $environment_texte;
					$environment_array["dbname"] = $environment_dbname;
					$environment_array["dbport"] = $environment_port;
					$environment_array["dbhost"] = $environment_host;
                    $environment_array["dbusername"] = $environment_username;
                    $environment_array["dbpassword"] = $environment_password;
					$environments_array[] = $environment_array;
				}
			}

		}
	}
	
	if ($environment_error == TRUE) {
		logErrorMsg("Au moins un environnement de la consolidation n'est pas correct");
		return FALSE;
	}
	
	
	$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
	$ret = $iCTI_connexion->connect();

	
	if (!$ret) {
		logErrorMsg("La connexion PostgreSQL iCTI a échoué");
		return FALSE;
	}

	if ($iCTI_rmtip == "") {
        $SERVER_name = php_uname('n');
		$iCTI_rmtip = @gethostbyname($SERVER_name);

		if ($iCTI_rmtip == "") {
			exec('ipconfig.exe', $ipconfig);

			foreach ($ipconfig as $ipconfig_line) {
				if (eregi('IP Address', $line)) {
					list($t, $ip) = split(':', $line);
					$iCTI_rmtip = $ip;
				}
				if (eregi('Adresse IPv4', $line)) {
					list($t, $ip) = split(':', $line);
					$iCTI_rmtip = $ip;
				}
			}
		}
	}
	
	return $iCTI_connexion;


}



function iCTI_disconnect() {

	global $iCTI_connexion;
	$iCTI_connexion->close();
}





    
?>