//===========================================================================
//
//  File Name:    Setup.rul
//
//  Description:  Blank setup main script file
//
//  Comments:     Blank setup is an empty setup project. If you want to
//				  create a new project via. step-by step instructions use the
//				  Project Assistant.
//
//===========================================================================

// Included header files ----------------------------------------------------
#include "ifx.h"
#include "iswi.h"
#include "DlgMySqlParameters2.rul"
#include "DlgMySetupType.rul"
#include "Q100157.rul"     
#include "scramble.rul"

#define XEMELIOS_PRODUCT_VERSION "3.3" 
#define XEMELIOS_ROOT_RELATIVE_PATH "Xemelios\\root"
#define XEMELIOS_MYSQL_RELATIVE_PATH "MySQLServer\\MySQL Server 5.0"
#define XEMELIOS_INSTALL_CLIENT "Client"
#define XEMELIOS_INSTALL_SERVEUR "Serveur"
#define XEMELIOS_INSTALL_MONOPOSTE "Monoposte"
#define XEMELIOS_DEFAULT_SCHEMA "xemelios"

#define MYSQL_DEFAULT_PORT "3306"

// Note: In order to have your InstallScript function executed as a custom
// action by the Windows Installer, it must be prototyped as an 
// entry-point function.

// The keyword export identifies MyFunction() as an entry-point function.
// The argument it accepts must be a handle to the Installer database.
    
/* export prototype MyFunction(HWND); */      
export prototype ExFn_WriteDematProperties(HWND); 
export prototype ExFn_WriteMySqlProperties(HWND); 
export prototype ExFn_WriteInstallScript1(STRING,STRING,STRING);
export prototype ExFn_WriteInstallScript2(STRING,STRING,STRING);
export prototype ExFn_WriteInstallScriptBat(STRING,STRING,STRING,STRING,STRING,STRING,BYREF STRING);
export prototype ExFn_WriteXemeliosBat();
export prototype readFileInList(BYREF NUMBER,STRING,STRING);
export prototype patchConfigFiles();
export prototype ExFn_WriteAuthenticationProperties(HWND);
export prototype debug(STRING);
export prototype NUMBER showInformationExit(STRING);
                                
STRING svGlobalSetupType; // Client, Serveur, Monoposte
STRING svGlobalIsMySql; // indicateur de presence de MySql
STRING svGlobalIsMySqlV5; // indicateur de presence de MySql V5
STRING svGlobalIsMySqlForXemelios; // indicateur d'install de MySql par Xemelios
STRING svGlobalDoInstallMySql;
STRING svGlobalDoSetupMySql; // 
STRING svGlobalDoSetupMySqlFilePath; // 
STRING svGlobalDoSetupMySqlArgs; // 
STRING svGlobalMySqlServerName;
STRING svGlobalMySqlServerPort;
STRING svGlobalMySqlSchemaName;
STRING svGlobalMySqlServerPassword;
STRING svGlobalMySqlXemeliosUser;
STRING svGlobalMySqlXemeliosPassword;
BOOL   svGlobalConfigTresor;
BOOL   svGlobalProductRemoved;



//---------------------------------------------------------------------------
// OnFirstUIBefore
//
// The OnFirstUIBefore event is called by the framework when the setup is
// running in first install mode. By default this event displays UI allowing
// the end user to specify installation parameters.
//---------------------------------------------------------------------------
function OnFirstUIBefore()
    NUMBER nResult, nvSize, nUser, nvNumTmp, nvType, nResult1;
    STRING szTitle, szMsg, szQuestion, svServerName, svServerPort, szFile, svSetupType, svSchema, svDir;
    STRING szInfoSystem, svResult;
    STRING szLicenseFile;
    LIST list, listStartCopy;
	BOOL bCustom; 
    LIST    listData;  
    STRING FilePath;
    STRING szValueBuf;
    INT cchValueBuf;
    STRING szNextDialog, svTemp; 
    STRING svMySqlServerPassword, svXemeliosUser, svXemeliosPassword;
    BOOL   bAfficheSqlParams; 
    STRING title ;
    STRING msg ;
    NUMBER installType ;
    BOOL advanced ;     // affichage de la configuration avancee
    BOOL configTresor;	// prédéfinition pour l'authentification LDAP du trésor

begin
//	MessageBox("OnFirstUIBefore",INFORMATION);
	bCustom = Is(USER_ADMINISTRATOR,"");
	if(bCustom = FALSE) then
		MessageBox("Vous devez être Administrateur de la machine pour pouvoir installer Xemelios",SEVERE);
		Do(EXIT);
	else
		bCustom = FALSE;
	endif;
	// load scrambling table
	initializeScramble();
	// ================================================================
	// Infos système  
	//
	// ================================================================	
	szInfoSystem = "";
	if (GetSystemInfo (OS, nResult1, svResult) < 0) then
		MessageBox( "Impossible d'obtenir les informations sur le système d'exploitation.",SEVERE);
		abort;
	else
		switch (nResult1)
			case IS_WINDOWSNT:
				szInfoSystem = "NT";
			case IS_WINDOWS9X:
				GetSystemInfo (WINMINOR, nResult1, svResult);
				if (nResult1 < 10) then
					 szInfoSystem = "95";
				else
					 szInfoSystem = "98";
				endif;
		endswitch;
	endif; 
    
    
    svGlobalDoSetupMySql = "N";
	SHELL_OBJECT_FOLDER = @PRODUCT_NAME;	   
    
	svSetupType = XEMELIOS_INSTALL_MONOPOSTE;	
    szLicenseFile = SUPPORTDIR ^ "xemelios.LICENSE.txt";
	svServerName = "";
    svServerPort = MYSQL_DEFAULT_PORT; 
    svSchema = XEMELIOS_DEFAULT_SCHEMA ; 
    svDir = TARGETDIR;
    
Dlg_SdWelcome:
    szTitle = "";
    szMsg   = "";
    nResult = SdWelcome(szTitle, szMsg);
    if (nResult = BACK) goto Dlg_SdWelcome;
	
Dlg_SdLicense:
    nResult = SdLicense2 ("", "", "", szLicenseFile,FALSE);
    if (nResult = BACK) goto Dlg_SdWelcome; 
       
    if( nResult != YES ) then
    	abort;
    endif;
	

Dlg_SetupType:
    szTitle = "";
    szMsg   = "";
    title = "titre";
    msg = "Message";
    installType  =1;
    advanced = FALSE;
    configTresor = FALSE;

    nResult = MySetupType(title,msg,installType,advanced,svDir,configTresor);
    if(nResult = SETUPTYPE_BUTTON_BACK) then
    	goto Dlg_SdLicense;
    endif;
    switch(installType)
    	case 1: svSetupType=XEMELIOS_INSTALL_MONOPOSTE;
    	case 2: svSetupType=XEMELIOS_INSTALL_CLIENT;
    	case 3: svSetupType=XEMELIOS_INSTALL_SERVEUR;
    endswitch;
    // correction pour 3.0.4 - on installait pas à l'endroit spécifié
    INSTALLDIR=svDir;

    
    // on controle que l'utilisateur n'a pas choisi CUSTOM=>SERVER sous 98
    if(svSetupType = XEMELIOS_INSTALL_SERVEUR && szInfoSystem = "98" ) then
    	MessageBox("Sous Windows 98, vous ne pouvez pas réaliser d'installation Serveur.\nVeuillez faire un autre choix.",WARNING);
    	goto Dlg_SetupType;
    endif; 

	svGlobalIsMySql = "N";
	svGlobalIsMySqlV5 = "N";
	svGlobalDoInstallMySql = "N"; 
	svGlobalIsMySqlForXemelios = "N";
	svTemp = "";
	if( svSetupType = XEMELIOS_INSTALL_SERVEUR ) then                              
		// Il faut détecter si un mySql a été installé sur cette machine.
		// - Recherche d'une clé dans la base de registres  
		if (RegDBSetDefaultRoot (HKEY_LOCAL_MACHINE)  < 0) then
			MessageBox("Impossible de changer la clé de registre par défaut.", SEVERE);
			abort;
		endif;  
		
		nvNumTmp = -1; 
		nvType = REGDB_STRING;
   		RegDBGetKeyValueEx ("SOFTWARE\\DGCP\\xemelios", "MySqlLocation", nvType, svTemp,nvNumTmp);
		
	    if (RegDBKeyExist ("SOFTWARE\\MYSQL AB") < 0) then
		else
		    svGlobalIsMySql = "O";
		endif;    
				
		if ( svGlobalIsMySql = "O" && RegDBKeyExist ("SOFTWARE\\MYSQL AB\\MySQL Server 5.0") < 0) then
		    svGlobalIsMySqlV5 = "N";
		elseif( svGlobalIsMySql = "O" ) then
		    svGlobalIsMySqlV5 = "O";
		endif; 

		// 1er cas : MySql a été installé par qqun d'autre que Xemelios
		if( svGlobalIsMySql = "O" ) then
			MessageBox("Une version de MySql a été détectée sur votre poste. Ce composant ne sera donc pas installé par Xemelios. Reportez-vous à la documentation d'installation du produit pour effectuer son paramétrage.", INFORMATION);
			svGlobalDoInstallMySql = "N";
		elseif  (svTemp != "") then
			// 2eme cas : MySql a été installé par Xemelios
			if( AskYesNo("MySql a déjà été installé pour Xemelios dans le répertoire " + svTemp + ". Voulez-vous le réinstaller?",YES) = YES) then
				svGlobalDoInstallMySql = "O";
			endif;
		else
			// 3eme cas : MySql n'a pas été détecté sur le poste
			// Pas de mySql détécté. Doit-on l'installer?
			if( AskYesNo("Aucune version de MySql n'a été détectée sur votre poste. Voulez-vous l'installer?",YES) = YES) then
				svGlobalDoInstallMySql = "O";
			endif;
		endif;
	endif;	

	FeatureSelectItem (MEDIA, "Xemelios", TRUE);
	FeatureSelectItem (MEDIA, "License", TRUE);
	switch (svSetupType)
		case XEMELIOS_INSTALL_CLIENT:
			FeatureSelectItem (MEDIA, "ServerMySql", FALSE);
			FeatureSelectItem (MEDIA, "MySql", FALSE);
		case XEMELIOS_INSTALL_SERVEUR: 
			if (svGlobalDoInstallMySql != "O") then 
				FeatureSelectItem (MEDIA, "ServerMySql", FALSE); 
			else
				FeatureSelectItem (MEDIA, "ServerMySql", TRUE); 
			endif;			
			FeatureSelectItem (MEDIA, "MySql", FALSE);
		case XEMELIOS_INSTALL_MONOPOSTE:
			if(szInfoSystem = "98") then
				FeatureSelectItem (MEDIA, "MySql", TRUE);
				FeatureSelectItem (MEDIA, "ServerMySql", FALSE);
			else
				FeatureSelectItem (MEDIA, "ServerMySql", TRUE);
				FeatureSelectItem (MEDIA, "MySql", FALSE);
			endif;
		default:
			MessageBox ("An unspecified error occurred while choosing setup mode.", SEVERE);
			abort;
	endswitch;

    
    if (nResult = BACK) then
        goto Dlg_SdLicense;
    else
        nvSize = 0;
        FeatureCompareSizeRequired(MEDIA, INSTALLDIR, nvSize);
        if (nvSize != 0) then      
           	MessageBox(szSdStr_NotEnoughSpace, WARNING);
            goto Dlg_SetupType;
        endif;
		bCustom = FALSE;
    endif;    
    //bAfficheSqlParams = ((svSetupType = XEMELIOS_INSTALL_CLIENT && szInfoSystem != "98") || (svSetupType = XEMELIOS_INSTALL_SERVEUR && svGlobalDoInstallMySql = "O"));
    bAfficheSqlParams = advanced;
    
if( !bAfficheSqlParams) then	//  && svSetupType = XEMELIOS_INSTALL_SERVEUR
    // TODO add here predefined values for monoposte install
    svServerPort = "3306";
    svMySqlServerPassword = "manager";	// Maybe change this to xemelios
    svXemeliosUser = "xemelios";
    svXemeliosPassword = "xem_pass";
	if(svSetupType = XEMELIOS_INSTALL_SERVEUR ) then
    	svServerName = "localhost";
		goto Dlg_SdStartCopy;
	endif;
endif;

Dlg_SdDBParameters: 
    szTitle = "Paramètres de connexion au serveur";
    szMsg   = "Entrez le nom du serveur de base de données, son port et le nom du schéma.";    

    // Retrieve registration information.
	nResult = NEXT;
	if( svSetupType = XEMELIOS_INSTALL_CLIENT ) then
		if(advanced) then
    		nResult = SdRegisterUserEx (szTitle, szMsg, svServerName, svServerPort, svSchema);
    	else
    		nResult = AskText("Veuillez indiquer le serveur Xemelios auquel vous vous connectez.\nVous pouvez indiquer soit le nom du serveur, soit son adresse IP.",svServerName,svServerName);
    	endif;
    elseif (svSetupType = XEMELIOS_INSTALL_SERVEUR) then
    	if(advanced) then
    		if( svServerName = "" ) then 
    			GetEnvVar ( "COMPUTERNAME", svServerName );	
    		endif;
	    	nResult = MySqlParameters2(szTitle, szMsg, svServerName, svServerPort, svMySqlServerPassword);  
	    	if (nResult = BACK) then
	    		//MessageBox("BACK",INFORMATION); 
	    	elseif (nResult = NEXT) then 
	    		//MessageBox("NEXT",INFORMATION); 
	    	else
	    		Do(EXIT);
	    	endif; 
	    	svMySqlServerPassword = svGlobal_TURNAROUND_Password;
 			svServerPort = svGlobal_TURNAROUND_Port;
        	svServerName = svGlobal_TURNAROUND_Server; 
        else
        	// TODO: check if there is still something to do
       	endif;

    endif;
    
	if (nResult = BACK) goto Dlg_SetupType;

Dlg_SdUserDBParameters: 
    szTitle = "";
    szMsg   = ""; 
    if( svXemeliosUser = "" ) then
    	svXemeliosUser = "xemelios";  
    endif; 
	
	nResult = NEXT;
	if(advanced) then
   		nResult = SdRegisterUser (szTitle, szMsg, svXemeliosUser, svXemeliosPassword);
   	endif;
	if (nResult = BACK) goto Dlg_SdDBParameters;

Dlg_SdStartCopy:
    szTitle = "";
    szMsg   = "";
    listStartCopy = ListCreate( STRINGLIST );
    if( FeatureIsItemSelected( MEDIA, "Xemelios") = TRUE) then 
    	ListAddString(listStartCopy,"... Installation de Xemelios",AFTER);
    endif;
    if( FeatureIsItemSelected( MEDIA, "MySql") = TRUE) then 
    	ListAddString(listStartCopy,"... Installation du serveur MySql embarqué",AFTER);
    endif;
    if( FeatureIsItemSelected( MEDIA, "ServerMySql") = TRUE) then 
    	ListAddString(listStartCopy,"... Installation du serveur MySql",AFTER);
    endif;
    
    nResult = SdStartCopy( szTitle, szMsg, listStartCopy );			
    ListDestroy(listStartCopy);
	
	if (nResult = BACK) then 
		if( bAfficheSqlParams = TRUE) then
			goto Dlg_SdUserDBParameters;  
		else
			goto Dlg_SetupType;
		endif;
    endif;

    // setup default status
    Enable(STATUSEX);
    
    // Mise à jour des variables globales
    svGlobalSetupType = svSetupType ; 
	svGlobalMySqlServerName = svServerName;
	svGlobalMySqlServerPort = svServerPort;
	svGlobalMySqlSchemaName = svSchema;
	svGlobalMySqlServerPassword =  svMySqlServerPassword; 
	svGlobalMySqlXemeliosUser = svXemeliosUser;
	svGlobalMySqlXemeliosPassword = svXemeliosPassword;
	svGlobalConfigTresor = configTresor;

    return 0;
end;
        
function ExFn_WriteAuthenticationProperties(hMSI)
	LIST listID;
	STRING svTemplateFileName;
	STRING authenticationClass;
	STRING ldapUrl;
	STRING ldapDn;
	STRING line;
	STRING nvFileName;
	STRING nvFileDir;
	NUMBER nResult, nvFileHandle;
begin
    listID = ListCreate (STRINGLIST);
    if (listID = LIST_NULL) then
        MessageBox ("Erreur interne. Contactez la maintenance", SEVERE);
        abort;
    endif; 
	svTemplateFileName = SUPPORTDIR ^ "authentication.properties.template";
    OpenFileMode (FILE_MODE_NORMAL);
    if (ListReadFromFile (listID, svTemplateFileName) < 0) then
        // Report ListReadFromFile failure.
        MessageBox ("Impossible de lire " + svTemplateFileName + ".", SEVERE);
    else
	    nResult = ListGetFirstString (listID, line); 
	    if(svGlobalConfigTresor) then
	    	authenticationClass="fr.gouv.finances.cp.xemelios.auth.dgcp.Manager";
	    else
	    	authenticationClass="fr.gouv.finances.cp.xemelios.auth.basic.mysql.Manager";
	    endif;
	    // Loop while not at end of list.
	    while (nResult != END_OF_LIST)
			if(StrReplace(line,"<%AUTHENTICATION_CLASS%>",authenticationClass,0)>0) then
				ListSetCurrentString(listID,line);
			endif;
	        nResult = ListGetNextString (listID, line);
		endwhile;       
    endif;
    	// Set the file mode to append.
    	OpenFileMode (FILE_MODE_APPEND);  
    	nvFileDir = INSTALLDIR ^ "Xemelios" ^ "root";
    	nvFileName = "authentication.properties";

    	// Create a new file and leave it open.
    	if (CreateFile (nvFileHandle, nvFileDir, nvFileName) < 0) then
        	// Report the error.
        	MessageBox ("Impossible de créer le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
        	abort;
	    else
	        // Set the message to write to the file.	
	        if (ListWriteToFile (listID, nvFileDir ^ nvFileName) < 0) then
	            MessageBox ("Impossible d'écrire dans le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
	        endif;
	    endif;

	    // Close the file.
	    CloseFile (nvFileHandle);
end;        
    
//-------------------------------------------------------------------
//
//
//
// ----------------------------------------------------------------    
function ExFn_WriteDematProperties(hMSI)
    NUMBER  nvFileHandle, nResult, nvResult; 
    STRING  szTitle, szMsg, szOS, szInfo, svResult; 
    STRING  nvFileDir, nvFileName, nvItem;      
    STRING  svTemplateFileName, svTemplateLine,svTemp;  
    LIST listID;
begin                             
    listID = ListCreate (STRINGLIST);
    if (listID = LIST_NULL) then
        MessageBox ("Erreur interne. Contactez la maintenance", SEVERE);
        abort;
    endif; 
	svTemplateFileName = SUPPORTDIR ^ "xemelios.properties.template"; 
    
    OpenFileMode (FILE_MODE_NORMAL);
    if (ListReadFromFile (listID, svTemplateFileName) < 0) then
        // Report ListReadFromFile failure.
        MessageBox ("Impossible de lire " + svTemplateFileName + ".", SEVERE);
    else   
    	// On remplace les tokens   
	    // Get the operating system.
	    szInfo = "";
	    if (GetSystemInfo (OS, nvResult, svResult) < 0) then
	        MessageBox( "Impossible d'obtenir les informations sur le système d'exploitation.",SEVERE);
	        abort;
	    else
	        switch (nvResult)
	            case IS_WINDOWSNT:
	                szInfo = "NT";
	            case IS_WINDOWS9X:
	                GetSystemInfo (WINMINOR, nvResult, svResult);
	                if (nvResult < 10) then
	                     szInfo = "95";
	                else
	                     szInfo = "98";
	                endif;
	        endswitch;
	    endif; 
	    //MessageBox("OS : " + szInfo, INFORMATION);
    	
	    // Get the first number from the list.
	    nResult = ListGetFirstString (listID, nvItem); 
	    svTemp = TARGETDIR;
	    StrRemoveLastSlash ( svTemp ); 
	    StrReplace( svTemp,"\\","/",0);

	    // Loop while not at end of list.
	    while (nResult != END_OF_LIST)
	        StrReplace ( nvItem, "<%INSTALLDIR%>", svTemp, 0 );
        	StrReplace ( nvItem, "<%ADMINMENU%>", "true", 0 );
	        if( szInfo = "NT" ) then
	        	StrReplace ( nvItem, "<%PREFIXFILE%>", "file://", 0 );   
	        elseif ( szInfo = "95" || szInfo = "98") then
	        	StrReplace ( nvItem, "<%PREFIXFILE%>", "", 0 );   
	        else
	        	StrReplace ( nvItem, "<%PREFIXFILE%>", "file://", 0 );   
			endif;	
			        
	        ListSetCurrentString ( listID, nvItem ); 
	        // Get the next number from the list.
	        nResult = ListGetNextString (listID, nvItem);
	    endwhile;
	    
	    if(svGlobalConfigTresor) then
	    	ListAddString(listID,"http.proxyHost=proxy.bercy.cp",AFTER);
	    	ListAddString(listID,"http.proxyPort=3128",AFTER);
	    	ListAddString(listID,"xemelios.proxy.server=proxy.bercy.cp",AFTER);
	    	ListAddString(listID,"xemelios.proxy.port=3128",AFTER);
	    endif;

    	// Set the file mode to append.
    	OpenFileMode (FILE_MODE_APPEND);  
    	nvFileDir = INSTALLDIR ^ "Xemelios" ^ "root";
    	nvFileName = "xemelios.properties";

    	// Create a new file and leave it open.
    	if (CreateFile (nvFileHandle, nvFileDir, nvFileName) < 0) then
        	// Report the error.
        	MessageBox ("Impossible de créer le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
        	abort;
	    else
	        // Set the message to write to the file.	
	        if (ListWriteToFile (listID, nvFileDir ^ nvFileName) < 0) then
	            MessageBox ("Impossible d'écrire dans le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
	        endif;
	    endif;

	    // Close the file.
	    CloseFile (nvFileHandle);
    endif;
    

end;

//-------------------------------------------------------------------
//
//
//
// ----------------------------------------------------------------    

function ExFn_WriteMySqlProperties(hMSI)
    NUMBER  nvFileHandle, nResult; 
    STRING  szTitle, szMsg, szOS; 
    STRING  nvFileDir, nvFileName, nvItem;      
    STRING  svTemplateFileName, svTemplateLine, svPort;  
    STRING szInfoSystem, svResult;
    NUMBER nResult1;
    LIST listID;
begin                             
	szInfoSystem = "";
	if (GetSystemInfo (OS, nResult1, svResult) < 0) then
		MessageBox( "Impossible d'obtenir les informations sur le système d'exploitation.",SEVERE);
		abort;
	else
		switch (nResult1)
			case IS_WINDOWSNT:
				szInfoSystem = "NT";
			case IS_WINDOWS9X:
				GetSystemInfo (WINMINOR, nResult1, svResult);
				if (nResult1 < 10) then
					 szInfoSystem = "95";
				else
					 szInfoSystem = "98";
				endif;
		endswitch;
	endif; 

    listID = ListCreate (STRINGLIST);
    if (listID = LIST_NULL) then
        MessageBox ("Erreur interne. Contactez la maintenance", SEVERE);
        abort;
    endif; 
	svTemplateFileName = SUPPORTDIR ^ "mysql.properties.template"; 
    
    OpenFileMode (FILE_MODE_NORMAL);
    if (ListReadFromFile (listID, svTemplateFileName) < 0) then
        // Report ListReadFromFile failure.
        MessageBox ("Impossible de lire " + svTemplateFileName + ".", SEVERE);
    else   
    	// On remplace les tokens   
    	
	    // Get the first number from the list.
	    nResult = ListGetFirstString (listID, nvItem);
	    // Loop while not at end of list.
	    while (nResult != END_OF_LIST)
	        if( svGlobalSetupType = XEMELIOS_INSTALL_MONOPOSTE && szInfoSystem = "98") then
	        	StrReplace ( nvItem, "<%DRIVERCLASS%>", "com.mysql.embedded.jdbc.MySqlEmbeddedDriver", 0 );
	        else
	        	StrReplace ( nvItem, "<%DRIVERCLASS%>", "com.mysql.jdbc.Driver", 0 );
	        endif;
            if( svGlobalMySqlServerPort = MYSQL_DEFAULT_PORT ) then
            	svPort = "" ;                              
            else
            	svPort = ":" + svGlobalMySqlServerPort;                               
            endif;
            if(svGlobalMySqlServerName="") then
            	svGlobalMySqlServerName = "localhost";
            endif;
	        if( svGlobalSetupType = XEMELIOS_INSTALL_MONOPOSTE && szInfoSystem = "98") then
	        	StrReplace ( nvItem, "<%DBURL%>", "jdbc:mysql-embedded/xemelios", 0 );
	        else
	        	StrReplace ( nvItem, "<%DBURL%>", "jdbc:mysql://" + svGlobalMySqlServerName + svPort + "/" + svGlobalMySqlSchemaName, 0 );
	        endif;

	        StrReplace ( nvItem, "<%USER%>", svGlobalMySqlXemeliosUser, 0 );
	        StrReplace ( nvItem, "<%PASSWORD%>", scramblePassword(svGlobalMySqlXemeliosPassword), 0 );
			        
	        ListSetCurrentString ( listID, nvItem ); 
	        // Get the next number from the list.
	        nResult = ListGetNextString (listID, nvItem);
	    endwhile;

    	// Set the file mode to append.
    	OpenFileMode (FILE_MODE_APPEND);  
    	nvFileDir = INSTALLDIR ^ "Xemelios" ^ "root";
    	nvFileName = "mysql.properties";

    	// Create a new file and leave it open.
    	if (CreateFile (nvFileHandle, nvFileDir, nvFileName) < 0) then
        	// Report the error.
        	MessageBox ("Impossible de créer le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
        	abort;
	    else
	        // Set the message to write to the file.	
	        if (ListWriteToFile (listID, nvFileDir ^ nvFileName) < 0) then
	            MessageBox ("Impossible d'écrire dans le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
	        endif;
	    endif;

	    // Close the file.
	    CloseFile (nvFileHandle);
    endif;
    

end;
  
//-------------------------------------------------------------------
//
//
//
// ----------------------------------------------------------------    
function ExFn_WriteInstallScript1(NEWUSERXEM,NEWPASSXEM,NEWSCHEMAXEM)
    NUMBER  nvFileHandle, nResult, nvResult; 
    STRING  szTitle, szMsg, szOS, szInfo, svResult; 
    STRING  nvFileDir, nvFileName, nvItem;      
    STRING  svTemplateFileName, svTemplateLine,svTemp;  
    LIST listID;
begin                             
    listID = ListCreate (STRINGLIST);
    if (listID = LIST_NULL) then
        MessageBox ("Erreur interne. Contactez la maintenance", SEVERE);
        abort;
    endif; 
	svTemplateFileName = SUPPORTDIR ^ "installscript1.sql.template"; 
    
    OpenFileMode (FILE_MODE_NORMAL);
    if (ListReadFromFile (listID, svTemplateFileName) < 0) then
        // Report ListReadFromFile failure.
        MessageBox ("Impossible de lire " + svTemplateFileName + ".", SEVERE);
    else   
    	// On remplace les tokens   
    	
	    // Get the first number from the list.
	    nResult = ListGetFirstString (listID, nvItem); 

	    // Loop while not at end of list.
	    while (nResult != END_OF_LIST)
	        StrReplace ( nvItem, "<%NEWUSERXEM%>", NEWUSERXEM, 0 );
        	StrReplace ( nvItem, "<%NEWPASSXEM%>", NEWPASSXEM, 0 );
        	StrReplace ( nvItem, "<%NEWSCHEMAXEM%>", NEWSCHEMAXEM, 0 );
			        
	        ListSetCurrentString ( listID, nvItem ); 
	        // Get the next number from the list.
	        nResult = ListGetNextString (listID, nvItem);
	    endwhile;

    	// Set the file mode to append.
    	OpenFileMode (FILE_MODE_APPEND);  
    	nvFileDir = TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH;
//    	nvFileDir = SUPPORTDIR;
    	nvFileName = "installscript1.sql";

    	// Create a new file and leave it open.
    	if (CreateFile (nvFileHandle, nvFileDir, nvFileName) < 0) then
        	// Report the error.
        	MessageBox ("Impossible de créer le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
        	abort;
	    else
	        // Set the message to write to the file.	
	        if (ListWriteToFile (listID, nvFileDir ^ nvFileName) < 0) then
	            MessageBox ("Impossible d'écrire dans le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
	        endif;
	    endif;

	    // Close the file.
	    CloseFile (nvFileHandle);
    endif;
    

end;
  
//-------------------------------------------------------------------
//
//
//
// ----------------------------------------------------------------    
function ExFn_WriteInstallScript2(NEWUSERXEM,NEWPASSXEM,NEWSCHEMAXEM)
    NUMBER  nvFileHandle, nResult, nvResult; 
    STRING  szTitle, szMsg, szOS, szInfo, svResult; 
    STRING  nvFileDir, nvFileName, nvItem;      
    STRING  svTemplateFileName, svTemplateLine,svTemp;  
    LIST listID;
begin                             
    listID = ListCreate (STRINGLIST);
    if (listID = LIST_NULL) then
        MessageBox ("Erreur interne. Contactez la maintenance", SEVERE);
        abort;
    endif; 
	svTemplateFileName = SUPPORTDIR ^ "installscript2.sql.template"; 
    
    OpenFileMode (FILE_MODE_NORMAL);
    if (ListReadFromFile (listID, svTemplateFileName) < 0) then
        // Report ListReadFromFile failure.
        MessageBox ("Impossible de lire " + svTemplateFileName + ".", SEVERE);
    else   
    	// On remplace les tokens   
    	
	    // Get the first number from the list.
	    nResult = ListGetFirstString (listID, nvItem); 

	    // Loop while not at end of list.
	    while (nResult != END_OF_LIST)
	        StrReplace ( nvItem, "<%NEWUSERXEM%>", NEWUSERXEM, 0 );
        	StrReplace ( nvItem, "<%NEWPASSXEM%>", NEWPASSXEM, 0 );
        	StrReplace ( nvItem, "<%NEWSCHEMAXEM%>", NEWSCHEMAXEM, 0 );
			        
	        ListSetCurrentString ( listID, nvItem ); 
	        // Get the next number from the list.
	        nResult = ListGetNextString (listID, nvItem);
	    endwhile;

    	// Set the file mode to append.
    	OpenFileMode (FILE_MODE_APPEND);  
    	nvFileDir = TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH;
//    	nvFileDir = SUPPORTDIR;
    	nvFileName = "installscript2.sql";

    	// Create a new file and leave it open.
    	if (CreateFile (nvFileHandle, nvFileDir, nvFileName) < 0) then
        	// Report the error.
        	MessageBox ("Impossible de créer le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
        	abort;
	    else
	        // Set the message to write to the file.	
	        if (ListWriteToFile (listID, nvFileDir ^ nvFileName) < 0) then
	            MessageBox ("Impossible d'écrire dans le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
	        endif;
	    endif;

	    // Close the file.
	    CloseFile (nvFileHandle);
    endif;
    

end;                        
//-------------------------------------------------------------------
//
//
//
// ----------------------------------------------------------------    
function ExFn_WriteInstallScriptBat(oldPathRoot,newPathRoot,schemaName,newUser,oldPathUser,newPathUser,scriptFile)
    NUMBER  nvFileHandle, nResult, nvResult; 
    STRING  szTitle, szMsg, szOS, szInfo, svResult; 
    STRING  nvFileDir, nvFileName, nvItem;
    STRING nvTargetDir;      
    STRING  svTemplateFileName, svTemplateLine;
    STRING svTemp;
    LIST listID;
begin       
//	MessageBoxEx ( "ExFn_WriteInstallScriptBat :\noldPathRoot="+oldPathRoot+"\nnewPathRoot="+newPathRoot+"\nschemaName="+schemaName+"\nnewUser="+newUser+"\noldPathUser="+oldPathUser+"\nnewPathUser="+newPathUser,"Dans la fonction",INFORMATION);

	nvTargetDir = TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH;
	LongPathToQuote (nvTargetDir, TRUE); 
	svTemp = TARGETDIR;
    StrRemoveLastSlash ( svTemp ); 
	LongPathToQuote (svTemp, TRUE); 
  
    listID = ListCreate (STRINGLIST);
    if (listID = LIST_NULL) then
        MessageBox ("Erreur interne. Contactez la maintenance", SEVERE);
        abort;
    endif; 
	svTemplateFileName = SUPPORTDIR ^ "initPwdCommand.bat.template"; 
    
    OpenFileMode (FILE_MODE_NORMAL);
    if (ListReadFromFile (listID, svTemplateFileName) < 0) then
        // Report ListReadFromFile failure.
        MessageBox ("Impossible de lire " + svTemplateFileName + ".", SEVERE);
    else   
    	// On remplace les tokens   
    	
	    // Get the first number from the list.
	    nResult = ListGetFirstString (listID, nvItem); 

	    // Loop while not at end of list.
	    while (nResult != END_OF_LIST)
	    	// correction 3.1.1
        	StrReplace ( nvItem, "<%TARGETDRIVE%>", TARGETDISK, 0 );
	        StrReplace ( nvItem, "<%LOGFILE%>", "error.log", 0 );	// nvTargetDir + \\
        	StrReplace ( nvItem, "<%SQLINSTALLDIR%>", nvTargetDir, 0 );
        	StrReplace ( nvItem, "<%OLDPATHROOT%>", oldPathRoot, 0 );
        	StrReplace ( nvItem, "<%NEWPATHROOT%>", newPathRoot, 0 );
        	StrReplace ( nvItem, "<%SCHEMANAME%>", schemaName, 0 );
        	StrReplace ( nvItem, "<%NEWUSER%>", newUser, 0 );
        	StrReplace ( nvItem, "<%OLDPASSUSER%>", oldPathUser, 0 );
        	StrReplace ( nvItem, "<%NEWPASSUSER%>", newPathUser, 0 );
        	StrReplace ( nvItem, "<%SUPPORTDIR%>", svTemp, 0 );
			        
	        ListSetCurrentString ( listID, nvItem ); 
	        // Get the next number from the list.
	        nResult = ListGetNextString (listID, nvItem);
	    endwhile;

    	// Set the file mode to append.
    	OpenFileMode (FILE_MODE_APPEND);  
    	nvFileDir = TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH;
    	//nvFileDir = SUPPORTDIR;
    	nvFileName = "initPwdCommand.bat";

    	// Create a new file and leave it open. 
//    	MessageBox("Creation de "+nvFileDir+" - "+nvFileName,INFORMATION);
    	if (CreateFile (nvFileHandle, nvFileDir, nvFileName) < 0) then
        	// Report the error.
        	MessageBox ("Impossible de créer le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
        	abort;
	    else
	        // Set the message to write to the file.	
	        if (ListWriteToFile (listID, nvFileDir ^ nvFileName) < 0) then
	            MessageBox ("Impossible d'écrire dans le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
	        endif;
//	        CopyFile(nvFileDir ^ nvFileName, nvFileDir ^ "initMoi.bat.txt");
	    endif;

	    // Close the file.
	    CloseFile (nvFileHandle);  
//	    MessageBox("Fichier cree",INFORMATION);
    endif;
    
    scriptFile = nvFileDir ^ nvFileName; 
    

end;

//---------------------------------------------------------------------------
// OnEnd
//
// The OnEnd event is called at the end of the setup. This event is not
// called if the setup is aborted.
//---------------------------------------------------------------------------
function OnEnd() 
	LIST lst;
	STRING nvFileDir, nvFileName;
	NUMBER nvFileHandle;
	STRING DOCUMENT_DEFS_DIR, PERSISTENCE_DIR, LIB_DIR, DOC_DIR;
	LONG ret;
begin    
//MessageBox("OnEnd",INFORMATION);
	if( MAINTENANCE && !svGlobalProductRemoved ) then
		patchConfigFiles();
		// suppression des vieux fichiers
	else
		if( svGlobalDoSetupMySql = "O" ) then
			LongPathToQuote(  svGlobalDoSetupMySqlFilePath , TRUE);
			if LaunchAppAndWait ( "cmd.exe", "/c " + svGlobalDoSetupMySqlFilePath , LAAW_OPTION_WAIT | LAAW_OPTION_HIDDEN )<0 then	// | LAAW_OPTION_HIDDEN
				MessageBox("L'application " + svGlobalDoSetupMySqlFilePath +" " + svGlobalDoSetupMySqlArgs + " n'a pas pu être exécutée.", SEVERE);
				MessageBox("La configuration de mySql n'a pas été effectuée.", SEVERE);
				return 0;
			endif; 
			DeleteFile (TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH ^ "installscript1.sql"); 
			DeleteFile (TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH ^ "installscript2.sql");
			DeleteFile (TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH ^ " *.template" );
			DeleteFile (TARGETDIR ^ XEMELIOS_MYSQL_RELATIVE_PATH ^ " initPwdCommand.bat" );
		endif;
		DeleteFile (TARGETDIR ^ XEMELIOS_ROOT_RELATIVE_PATH ^ "mysql.properties.template"); 
		DeleteFile (TARGETDIR ^ XEMELIOS_ROOT_RELATIVE_PATH ^ "xemelios.bat.template"); 
		DeleteFile (TARGETDIR ^ XEMELIOS_ROOT_RELATIVE_PATH ^ "xemelios.properties.template");
		DeleteFile (TARGETDIR ^ XEMELIOS_ROOT_RELATIVE_PATH ^ "authentication.properties.template");
	endif;

//	if( !FeatureIsItemSelected( MEDIA, "ServerMySql") && FeatureIsItemSelected( MEDIA, "MySql")) then
//	endif;

	DOCUMENT_DEFS_DIR = INSTALLDIR ^ "Xemelios" ^ "root" ^ "documents-def";
	PERSISTENCE_DIR = DOCUMENT_DEFS_DIR ^ "persistence-config";   
	LIB_DIR = INSTALLDIR ^ "Xemelios" ^ "root" ^ "lib";
	DOC_DIR = INSTALLDIR ^ "Xemelios" ^ "root" ^ "doc";
	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "documents.xml");		
	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "etatPaye.xsl");
	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "etatVersement.xsl");
// 	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "etatVersement.xml");
	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "nomenclature-import.xsl");
	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "nomenclature-import-versement.xsl");
	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "nomenclature-paye.xsl");
	ret = DeleteFile(DOCUMENT_DEFS_DIR ^ "nomenclature-versement.xsl");
	ret = DeleteFile(PERSISTENCE_DIR ^ "etatPaye-import-mysql.xsl");
	ret = DeleteFile(PERSISTENCE_DIR ^ "etatVersement-import-mysql.xsl");
	ret = DeleteFile(PERSISTENCE_DIR ^ "index.xsl");
	ret = DeleteFile(PERSISTENCE_DIR ^ "paye-persistence.xml");
	ret = DeleteFile(PERSISTENCE_DIR ^ "versement-persistence.xml");
	ret = DeleteDir(PERSISTENCE_DIR,ALLCONTENTS); 
	 
	ret = DeleteFile(LIB_DIR ^ "mysql-connector-java-3.1.10-bin.jar");
    ret = DeleteFile(LIB_DIR ^ "data-impl.jar");
    ret = DeleteFile(LIB_DIR ^ "import-batch.jar");  
    
    ret = DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "drop-user.jar");

end;
//---------------------------------------------------------------------------
// OnUninstall
//
// The OnUninstall event is called when uninstallation is started by the
// end user from either the Add/Remove programs or by clicking on
// setup.exe again, after the product has already been installed.
// This event will only be triggered if the "Enable Maintenance"
// property in General Information\Project Properties is set to
// No.  If this property is set to Yes, then the Maintenance
// events will get triggered.  This event is similar to an IS5
// uninstallation.
//---------------------------------------------------------------------------
function OnUninstall()
	BOOL   bvOpt1, bvOpt2;
	string szTitle, szMsg1, szMsg2, szOpt1, szOpt2, svResult, szCaption;
begin
//MessageBox("OnUninstall",INFORMATION);
	svResult = SdLoadString(ISWI_IS5_UNINST_MSG);
	szCaption = SdLoadString(IFX_ONMAINTUI_CAPTION); 
	//MessageBox("Call uninstall",INFORMATION);
	Sprintf (svResult, svResult, @PRODUCT_NAME);
	if (IDCANCEL = SprintfBox(MB_OKCANCEL, szCaption, svResult)) then
		abort; 
	endif;
	
	Enable(STATUSEX);

	//////////////////////////////////////
	//DO NOT DELETE.  The below code will
	//initiate the uninstallation process.
	ComponentRemoveAll();
	ComponentTransferData(MEDIA);
	//////////////////////////////////////
	
	Disable(STATUSEX);

	bvOpt1 = FALSE;
	bvOpt2 = FALSE;
	szMsg1 = SdLoadString(IFX_SDFINISH_MAINT_MSG1);
	szTitle = SdLoadString(IFX_SDFINISH_MAINT_TITLE);
	SdFinishEx(szTitle, szMsg1, szMsg2, szOpt1, szOpt2, bvOpt1, bvOpt2);
end;

//function OnBegin()
//STRING szKey, szName, svValue, msg;
//NUMBER nvSize, nvType;
//BOOL shouldAbort;
//begin
//	if (RegDBSetDefaultRoot (HKEY_LOCAL_MACHINE)  < 0) then
//		MessageBox("Impossible de changer la clé de registre par défaut.", SEVERE);
//		abort;
//	endif;
//
//    szKey     = "SOFTWARE\\DGCP\\xemelios";
//    szName   = "Version";
//    svValue="0";
//        
//    RegDBGetKeyValueEx(szKey,szName,nvType,svValue,nvSize);
    
    //MessageBox("Version read: "+svValue,INFORMATION);
    
//    if(svValue!="0") then
//    	shouldAbort = TRUE;
//    	// on a lu une clef, on peut supposer qu'il y a un Xemelios d'installé
//    	if(svValue="3.1.2b") then    
//    		msg="Xemelios V3.1.2b est installé sur cette station.\nPour le mettre à jour, démarrez Xemelios, et allez dans\nFichier / Mises à jour...";
//    	elseif(svValue=XEMELIOS_PRODUCT_VERSION) then
//    		shouldAbort = FALSE;
//    		//MaintenanceStart();
//    		OnUninstall(); 
//    		abort;
//    	else
//    		msg="Xemelios "+svValue+" est installé sur cette station. \nPour le mettre à jour, installez Xemelios V3.1.2b disponible sur\nhttp://admisource.gouv.fr/projects/xemelios/\nPuis utilisez l'utilitaire intégré de mise à jour accessible depuis\nFichier / Mises à jour...";
//    	endif;               
//    	if(shouldAbort) then
//    		MessageBox(msg,INFORMATION);
//    		abort;
//    	endif;
//    endif;
//        
//end;
//---------------------------------------------------------------------------
// OnMaintUIBefore
//
// The OnMaintUIBefore event is called by the framework when the setup is
// running in maintenance mode. By default this event displays UI that
// allows the end user to add or remove features, repair currently
// installed features or uninstall the application.
//---------------------------------------------------------------------------
function OnMaintUIBefore()
	NUMBER nResult, nType;
	STRING szTitle, szMsg, svDir, svResult, szCaption;   
	
    STRING szKey, szClass, szKeyRoot, svLogFile;
    NUMBER nResult1, nResult2, nServiceState;  
    
    STRING szNumName, szNumValue, svNumValue, szInfo;
    NUMBER nSize, nvType, nvSize;
    
    STRING szServiceName, szServiceDisplayName, szServiceDescription, szServicePathFile, szStartServiceArgs;
    BOOL bStartService; 
	
begin
//MessageBox("OnMaintUIBefore",INFORMATION);
	bStartService = Is(USER_ADMINISTRATOR,"");
	if(bStartService = FALSE) then
		MessageBox("Vous devez être Administrateur de la machine pour pouvoir installer Xemelios",SEVERE);
		Do(EXIT);
	else
		bStartService = FALSE;
	endif;
	// TO DO: if you want to enable background, window title, and caption bar title   								
	// SetTitle( @PRODUCT_NAME, 24, WHITE );					
	// SetTitle( @PRODUCT_NAME, 0, BACKGROUNDCAPTION );  			
	// SetColor(BACKGROUND,RGB (0, 128, 128));					
	// Enable( FULLWINDOWMODE );						
	// Enable( BACKGROUND );							
	if( AskYesNo("Voulez-vous vraiment supprimer Xemelios et l'ensemble de ses composants ?",NO) = NO) then
		abort;
	endif;
    // PO : on supprime tout
    nType = REMOVEALL; 
    
	// ================================================================
	// Infos système  
	//
	// ================================================================	
	szInfo = "";
	if (GetSystemInfo (OS, nResult1, svResult) < 0) then
		MessageBox( "Impossible d'obtenir les informations sur le système d'exploitation.",SEVERE);
		abort;
	else
		switch (nResult1)
			case IS_WINDOWSNT:
				szInfo = "NT";
			case IS_WINDOWS9X:
				GetSystemInfo (WINMINOR, nResult1, svResult);
				if (nResult1 < 10) then
					 szInfo = "95";
				else
					 szInfo = "98";
				endif;
		endswitch;
	endif; 

    if( szInfo = "NT" ) then
		// ================================================================
		// Arrêt du service
		//
		// ================================================================	
		szServiceName =  "MySQLForXemelios";
        nServiceState = -1; 
        if( ServiceExistsService ( szServiceName ) ) then
	        if( ServiceGetServiceState( szServiceName, nServiceState ) < ISERR_SUCCESS ) then
				//GetExtendedErrInfo ( svScriptFile, nvLineNumber, nvError );
				//MessageBox ("Impossible d'installer ou de démarrer le service MySQL :" + FormatMessage ( nvError ) , SEVERE);
				//MessageBox("La configuration de mySql n'a pas été effectuée.", SEVERE);
				//return 0;
				nServiceState = SERVICE_STOPPED;
	        endif; 
	        
	        // Si le service est démarré, on essaie de l'arrêter 
	        if( nServiceState = SERVICE_RUNNING ) then
		        ServiceStopService( szServiceName );
			endif;
			
			// on tente de le supprimer
			if( ServiceRemoveService ( szServiceName ) < ISERR_SUCCESS ) then
				MessageBox ( "Impossible de supprimer le service "+szServiceName , WARNING );
			endif;
		endif;
		       
	endif;
	    
    goto End_Dialogs;
Dlg_Start:

    // Added in Version 9.5 - Support for REMOVEONLY option.
    if( !REMOVEONLY ) then
		// In standard mode show maintenance dialog
		Disable(BACKBUTTON);
		nType = SdWelcomeMaint(szTitle, szMsg, MODIFY);
		Enable(BACKBUTTON);
	else
        // Hide the initial progress dialog as otherwise the user can
        // click on it, and hide the MessageBox.
        Disable( DIALOGCACHE );

        // In RemoveOnly mode, set to remove.
        nType = REMOVEALL;
    endif;
	
	// Show Uninstall Confirmation Dialog
    if ( nType = REMOVEALL ) then
		nResult = MessageBox( SdLoadString( IFX_MAINTUI_MSG ), MB_YESNO );
		if (nResult != IDYES ) then
            
            if( REMOVEONLY ) then
                // In REMOVEONLY mode, abort the setup.
                abort;
            else
                // In non-REMOVEONLY mode, redisplay the previous dialog.
			    goto Dlg_Start;
            endif;

		endif;
	endif;

	nResult = NEXT;

Dlg_SdFeatureTree:
	if (nType = MODIFY) then
		szTitle = "";
		szMsg = "";
		nResult = SdFeatureTree(szTitle, szMsg, INSTALLDIR, "", 2);
		if (nResult = BACK) goto Dlg_Start;
	endif;
	
End_Dialogs :
	switch(nType)
		case REMOVEALL: FeatureRemoveAll();
		case REPAIR:    FeatureReinstall();
	endswitch;
    
	// setup default status 
	SetStatusWindow(0, "");
	Enable(STATUSEX);
	StatusUpdate(ON, 100);
	svGlobalProductRemoved = TRUE;
end; 

//-------------------------------------------------------------------
//
//
//
// ----------------------------------------------------------------    
function ExFn_WriteXemeliosBat()
    NUMBER  nvType,nvFileHandle, nResult, nvResult,nvNumTmp; 
    STRING  szTitle, szMsg, szOS, szInfo, svResult,svTemp; 
    STRING  nvFileDir, nvFileName, nvItem, nvTargetDir;      
    STRING  svTemplateFileName, svTemplateLine,svJavaHome;  
    LIST listID;
begin                                 
	svTemp = TARGETDIR ^ XEMELIOS_ROOT_RELATIVE_PATH;
    StrRemoveLastSlash ( svTemp ); 
    svTemp = svTemp + "\\";

	if (RegDBSetDefaultRoot (HKEY_LOCAL_MACHINE)  < 0) then
		MessageBox("Impossible de changer la clé de registre par défaut.", SEVERE);
		abort;
	endif;  
		
	nvNumTmp = -1; 
	nvType = REGDB_STRING;
	if (RegDBGetKeyValueEx ("SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.5", "JavaHome", nvType, svJavaHome,nvNumTmp) < 0) then
       	// On ignore
   	endif;  
   	
   	if( svJavaHome = "" ) then
       	MessageBox ("Impossible de localiser le JRE 1.5. Vous devrez le spécifier dans le fichier " + TARGETDIR ^ XEMELIOS_ROOT_RELATIVE_PATH ^ "xemelios.bat", SEVERE);
       	svJavaHome = "Chemin d'accès au JRE 1.5";
   	endif;

    listID = ListCreate (STRINGLIST);
    if (listID = LIST_NULL) then
        MessageBox ("Erreur interne. Contactez la maintenance", SEVERE);
        abort;
    endif; 
	svTemplateFileName = SUPPORTDIR ^ "xemelios.bat.template"; 
    
    OpenFileMode (FILE_MODE_NORMAL);
    if (ListReadFromFile (listID, svTemplateFileName) < 0) then
        // Report ListReadFromFile failure.
        MessageBox ("Impossible de lire " + svTemplateFileName + ".", SEVERE);
    else   
    	// On remplace les tokens   
    	
	    // Get the first number from the list.
	    nResult = ListGetFirstString (listID, nvItem); 

	    // Loop while not at end of list. 
		LongPathToQuote (svTemp, TRUE); 
		LongPathToQuote (svJavaHome, TRUE); 
	    
	    while (nResult != END_OF_LIST)
        	StrReplace ( nvItem, "<%TARGETDRIVE%>", TARGETDISK, 0 );
        	StrReplace ( nvItem, "<%TARGETDIR%>", svTemp, 0 );
        	StrReplace ( nvItem, "<%JRE_5_DIR%>", svJavaHome, 0 );
			        
	        ListSetCurrentString ( listID, nvItem ); 
	        // Get the next number from the list.
	        nResult = ListGetNextString (listID, nvItem);
	    endwhile;

    	// Set the file mode to append.
    	OpenFileMode (FILE_MODE_APPEND);  
    	nvFileDir = TARGETDIR ^ XEMELIOS_ROOT_RELATIVE_PATH;
    	//nvFileDir = SUPPORTDIR;
    	nvFileName = "xemelios.bat";

    	// Create a new file and leave it open.
    	if (CreateFile (nvFileHandle, nvFileDir, nvFileName) < 0) then
        	// Report the error.
        	MessageBox ("Impossible de créer le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
        	abort;
	    else
	        // Set the message to write to the file.	
	        if (ListWriteToFile (listID, nvFileDir ^ nvFileName) < 0) then
	            MessageBox ("Impossible d'écrire dans le fichier "+ nvFileDir ^ nvFileName + ".", SEVERE);
	        endif;
	    endif;

	    // Close the file.
	    CloseFile (nvFileHandle);
    endif;
    

end;

function readFileInList(listId,filePath,fileName)
	NUMBER fileHandle,charCode,iCount;
	STRING s;
	STRING sTmp;
	STRING lastLine;
	NUMBER nRed;
	NUMBER tmpList;
begin
//	MessageBox("Reading "+filePath ^ fileName,INFORMATION);
	lastLine="";  
	listId = ListCreate(STRINGLIST);
	OpenFileMode(FILE_MODE_NORMAL);
	OpenFile(fileHandle,filePath,fileName);
	while(GetLine(fileHandle,s)=0)
		//SprintfBox(INFORMATION,"readFileInList: "+fileName,"%s",s);
		tmpList = ListCreate(STRINGLIST);
		StrGetTokens(tmpList,s,"\r\n");
		nRed = ListGetFirstString(tmpList,sTmp);
		while(nRed=0)
//			SprintfBox(INFORMATION,"Adding from "+fileName,"%s",sTmp);
			ListAddString(listId,sTmp,AFTER);
			sTmp="";
			nRed = ListGetNextString(tmpList,sTmp);
		endwhile;
		s="";
	endwhile; 

/*	nRead = ReadBytes(fileHandle,sTmp,0,100);
	while(nRead>=0)
		for iCount = 0 to StrLength(sTmp)
			charCode=sTmp[iCount] & 255;
			if(charCode=10 || charCode=11 || charCode=12 || charCode=13) then // LF, VT, FF, CR
				if(lastLine!="" && s!="") then
					ListAddString(listId, s, AFTER);
					SprintfBox(INFORMATION,"readFileInList: "+fileName,"%s",s);
					lastLine=s;
					s="";
				endif;
			else
				//s=s+sTmp;
				Sprintf(s,"%s%c",s,charCode);
			endif;
		endfor;
		sTmp="";
		SprintfBox(INFORMATION,"readFileInList: "+fileName,"%s",s);
		nRead = ReadBytes(fileHandle,sTmp,0,100);
	endwhile;*/
	CloseFile(fileHandle);
end;  
                            
//---------------------------------------------------------------------------
// checkPasswordDefinition
// This method checks if we are in maintenance, if installed version is a pre-3.0.0 finale,
// if client is installed, then it crypts password
//---------------------------------------------------------------------------
function patchConfigFiles()
	NUMBER listId, nResult, fileHandle, xPathLineNumber, versionLineNumber;
	STRING fileDir, fileName;
	STRING version, sTmp; 
	STRING clearPass, cryptedPass, sTmp2;
	BOOL bUpdatePresent, bXPathPresent, bComponentsPresent;
	STRING XPATH_line;
	STRING authenticationManager;
	BOOL bProxyHostPresent, bProxyPortPresent;
	BOOL bDateFormatPresent; 
	BOOL bNavigationForceReloadPresent;
	BOOL bResourcesLocationPresent;
	BOOL bExportXlsPresent;
	BOOL bJxlWarningsPresent;
	BOOL bPayeTotalisationPresent;
begin           
	version="";
	XPATH_line="javax.xml.xpath.XPathFactory\\:http\\://java.sun.com/jaxp/xpath/dom=com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl";
	if(!MAINTENANCE) then
		return 0;
	endif;
	initializeScramble();	
	if(FeatureIsItemSelected(MEDIA,"Xemelios")) then
    	fileDir = INSTALLDIR ^ "Xemelios" ^ "root";
    	fileName = "xemelios.properties";

		readFileInList(listId,fileDir,fileName);
    	nResult = ListGetFirstString (listId, sTmp);
    	while (nResult != END_OF_LIST)
    		debug(sTmp);
    		if(StrFindEx(sTmp,"xemelios.version=",0)=0) then
		    	StrSub(version,sTmp,17,1000);
		    	if(StrCompare(version,XEMELIOS_PRODUCT_VERSION)<0) then
					ListSetCurrentString(listId,"xemelios.version="+XEMELIOS_PRODUCT_VERSION);		    		
		    	endif;
		    	ListGetIndex(listId,versionLineNumber);
		    	debug("version="+version);
    		endif;
    		if(StrFindEx(sTmp,"xemelios.updater.source",0)=0) then
				bUpdatePresent = TRUE;
				debug("bUpdatePresent=TRUE");
			endif;
			if(StrFindEx(sTmp,"xemelios.components.filename",0)=0) then
				bComponentsPresent = TRUE;
				debug("bComponentsPresent=TRUE");
			endif;
			if(StrFindEx(sTmp,"javax.xml.xpath.XPathFactory",0)=0) then
				bXPathPresent = TRUE;
				debug("bXPathPresent=TRUE");
				ListGetIndex(listId,xPathLineNumber);
			endif;
			if(StrFindEx(sTmp,"help.url=",0)=0) then
				ListSetCurrentString(listId,"help.url=${navigator.url.prefix}${xemelios.prg}/doc/index.html");
			endif;
			if(StrFindEx(sTmp,"xemelios.date.format",0)=0) then
				bDateFormatPresent = TRUE;
			endif; 
			if(StrFindEx(sTmp,"xemelios.navigation.force-reload",0)=0) then
				bNavigationForceReloadPresent = TRUE;
			endif; 
			if(StrFindEx(sTmp,"xemelios.resources.location",0)=0) then
				bResourcesLocationPresent = TRUE;
			endif;
			if(StrFindEx(sTmp,"xemelios.paye.totalisation",0)=0) then
				bPayeTotalisationPresent = TRUE;
			endif;
			if(StrFindEx(sTmp,"xemelios.export.xls",0)=0) then
				bExportXlsPresent = TRUE;
			endif;
			if(StrFindEx(sTmp,"jxl.nowarnings",0)=0) then
				bJxlWarningsPresent = TRUE;
			endif;
			nResult = ListGetNextString(listId, sTmp);
		endwhile;
		
		// added for 3.1.0
		ListSetIndex(listId,LISTLAST);
		if(!bUpdatePresent) then
			ListAddString(listId,"xemelios.updater.source=http://projets.admisource.gouv.fr/xemelios/updates/update.xml",AFTER);
			bUpdatePresent=TRUE;
		endif;
		if(!bComponentsPresent) then
			ListAddString(listId,"xemelios.components.filename=${xemelios.prg}/root/components.xml",AFTER);
			bComponentsPresent=TRUE;
		endif;
		if(!bXPathPresent) then
			ListAddString(listId,XPATH_line,AFTER);
			bXPathPresent=TRUE;
		else
			ListSetIndex(listId,xPathLineNumber);
			ListCurrentString(listId,sTmp);
			debug("XPathPresent=true\n"+sTmp);
			if(StrCompare(sTmp,XPATH_line)!=0) then
				ListDeleteString(listId);
				ListAddString(listId,XPATH_line,AFTER);
			endif;
		endif;             
		// added 3.1.1
		if(!bDateFormatPresent) then
			ListAddString(listId,"xemelios.date.format=dd/MM/yyyy",AFTER);
			bDateFormatPresent = TRUE;
		endif;                
		// added to 3.2   
		if(!bNavigationForceReloadPresent) then
			ListAddString(listId,"xemelios.navigation.force-reload=false",AFTER);
			bNavigationForceReloadPresent=TRUE;
		endif;
		if(!bResourcesLocationPresent) then
			ListAddString(listId,"xemelios.resources.location=${xemelios.prg}/root/resources",AFTER);
			bResourcesLocationPresent=TRUE;
		endif;
		// added to 3.3
		if(!bPayeTotalisationPresent) then
			ListAddString(listId,"xemelios.paye.totalisation=false",AFTER);
			bPayeTotalisationPresent=TRUE;
		endif;
		if(!bExportXlsPresent) then
			ListAddString(listId,"xemelios.export.xls=true",AFTER);
			bExportXlsPresent=TRUE;
		endif;
		if(!bJxlWarningsPresent) then
			ListAddString(listId,"jxl.nowarnings=true",AFTER);
			bJxlWarningsPresent=TRUE;
		endif;
		ListWriteToFile(listId,fileDir ^ "xemelios.properties");
		// end add to 3.0.5		
		 
		if(version="") then	// pre-3.0.0, on ne notait pas encore le num de version dans xemelios.properties
			// il faut maintenant lire le mysql.properties pour crypter le mot de passe
			readFileInList(listId,fileDir,"mysql.properties");
			nResult = ListGetFirstString(listId, sTmp); 
			clearPass="";
			cryptedPass="";
			sTmp2="";
			while(nResult!=END_OF_LIST)
				if(StrFindEx(sTmp,"password=",0)=0) then
					// c'est celui la
					StrSub(clearPass,sTmp,9,1000);
					StrSub(sTmp2,clearPass,1,1);
					if("A"=sTmp2) then
						cryptedPass=clearPass;
					else
						cryptedPass=scramblePassword(clearPass);
					endif;
					ListSetCurrentString(listId,"password="+cryptedPass);
				endif;
				nResult = ListGetNextString(listId,sTmp);
			endwhile;         
			if(cryptedPass="" && clearPass="") then
				MessageBox("password non trouvé dans mysql.properties",WARNING);
			endif;
			DeleteFile(fileDir ^ "mysql.properties");
			if(ListWriteToFile(listId,fileDir ^ "mysql.properties")<0) then
				MessageBox("Impossible de mettre à jour "+fileDir ^ "mysql.properties", SEVERE);
			else
				// on met le xemelios.version dans xemelios.properties
				OpenFileMode(FILE_MODE_APPEND);
				OpenFile(fileHandle,fileDir,"xemelios.properties");
				WriteLine(fileHandle,"xemelios.version="+XEMELIOS_PRODUCT_VERSION);
				CloseFile(fileHandle);
			endif;

			if( FeatureIsItemSelected( MEDIA, "ServerMySql") = TRUE || FeatureIsItemSelected( MEDIA, "MySql") = TRUE) then
				listId = ListCreate(STRINGLIST);
				ListAddString(listId,"cd \""+INSTALLDIR ^ "Xemelios" ^ "root"+"\"", AFTER);
				ListAddString(listId, "java.exe -jar drop-user.jar", AFTER);
		    	OpenFileMode (FILE_MODE_APPEND);  
		    	fileDir = INSTALLDIR ^ "Xemelios" ^ "root";
		    	fileName = "drop-user.bat";
		
		    	if (CreateFile (fileHandle, fileDir, fileName) < 0) then
		        	MessageBox ("Impossible de créer le fichier "+ fileDir ^ fileName + ".", SEVERE);
		        	abort;
			    else
			        if (ListWriteToFile (listId, fileDir ^ fileName) < 0) then
			            MessageBox ("Impossible d'écrire dans le fichier "+ fileDir ^ fileName + ".", SEVERE);
			        endif;
			    endif;
		
			    CloseFile (fileHandle);
				LaunchAppAndWait(fileDir ^ fileName, "", LAAW_OPTION_WAIT | LAAW_OPTION_HIDDEN ); 		
			else                                                           
				// on ne le laisse pas trainer si il n'a pas ete utilise
				DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "drop-user.*");
				
			endif;
		else	// if (version="") 
			// on change le num de version dans xemelios.properties
			readFileInList(listId,fileDir,"xemelios.properties");
//   			nResult = ListGetFirstString (listId, sTmp);
//   			while (nResult != END_OF_LIST && version="")
//   				if(StrFindEx(sTmp,"xemelios.version=",0)=0) then
//	    			ListSetCurrentString(listId,"xemelios.version="+XEMELIOS_PRODUCT_VERSION);
//   				endif;
//				nResult = ListGetNextString(listId, sTmp);
//   			endwhile;
			ListSetIndex(listId,versionLineNumber);
			ListSetCurrentString(listId,"xemelios.version="+XEMELIOS_PRODUCT_VERSION);
   			ListWriteToFile(listId,fileDir ^ "xemelios.properties");
   			debug("changement de version dans xemelios.properties");
		endif;
	endif;
	DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "*.template");
	
	// on verifie que le drop-user.jar n'est pas dans lib
	DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "lib" ^ "drop-user.jar");
	DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "lib" ^ "index.html");
	
	// config tresor
	ListDeleteAll(listId);
   	fileDir = INSTALLDIR ^ "Xemelios" ^ "root";
   	fileName = "authentication.properties";
	readFileInList(listId,fileDir,fileName);
   	nResult = ListGetFirstString (listId, sTmp);
   	while (nResult != END_OF_LIST)
   		debug(sTmp);
   		if(StrFindEx(sTmp,"authentication.manager",0)=0) then
   			StrSub(authenticationManager,sTmp,23,1000);
   		endif;
		nResult = ListGetNextString(listId, sTmp);
	endwhile;
	if(authenticationManager!="fr.gouv.finances.cp.xemelios.auth.dgcp.Manager") then
		sTmp = "Si vous faites partie du réseau du Trésor, vous pouvez activer la configuration\n" +
			   "spécifique au réseau du Trésor. Cette configuration permet d'utiliser le même\n"+
			   "mot de passe que celui de votre messagerie.\n\n"+
			   "Si vous ne faites pas partie du réseau du Trésor, vous ne devez PAS activer cette configuration.\n\n"+
			   "Voulez-vous activer la configuration spécifique au réseau du Trésor ?";
		if(AskYesNo(sTmp,NO)=YES) then
			// authentication.properties
   			nResult = ListGetFirstString (listId, sTmp);
   			while (nResult != END_OF_LIST)
   				debug(sTmp);
   				if(StrFindEx(sTmp,"authentication.manager",0)=0) then
   					ListSetCurrentString(listId,"authentication.manager=fr.gouv.finances.cp.xemelios.auth.dgcp.Manager");
   				endif;
   				if(StrFindEx(sTmp,"auth.ldap.service.provider",0)>=0) then
   					ListSetCurrentString(listId,"auth.ldap.service.provider=com.sun.jndi.ldap.LdapCtxFactory");
   				endif;
   				if(StrFindEx(sTmp,"auth.ldap.server.url",0)>=0) then
   					ListSetCurrentString(listId,"auth.ldap.server.url=ldap://ldap.bercy.cp/");
   				endif;
   				if(StrFindEx(sTmp,"auth.ldap.userDn",0)>=0) then
   					ListSetCurrentString(listId,"auth.ldap.userDn=uid=%LOGIN%,ou=personnes,ou=dgcp,ou=mefi,o=gouv,c=fr ");
   				endif;
				nResult = ListGetNextString(listId, sTmp);
			endwhile;
			ListWriteToFile(listId,fileDir ^ fileName);
			// xemelios.properties
			ListDeleteAll(listId);
		   	fileName = "xemelios.properties";
			readFileInList(listId,fileDir,fileName);
   			nResult = ListGetFirstString (listId, sTmp);
   			while (nResult != END_OF_LIST)
   				debug(sTmp);
   				if(StrFindEx(sTmp,"http.proxyHost",0)=0) then
   					ListSetCurrentString(listId,"http.proxyHost=proxy.bercy.cp");
   					bProxyHostPresent = TRUE;
   				endif;
   				if(StrFindEx(sTmp,"http.proxyPort",0)=0) then
   					ListSetCurrentString(listId,"http.proxyPort=3128");
   					bProxyPortPresent = TRUE;
   				endif;
				nResult = ListGetNextString(listId, sTmp);
			endwhile;
			if(!bProxyHostPresent) then
	    		ListAddString(listId,"http.proxyHost=proxy.bercy.cp",AFTER);
	    	endif;
	    	if(!bProxyPortPresent) then
	    		ListAddString(listId,"http.proxyPort=3128",AFTER);
	    	endif;
    		ListAddString(listId,"xemelios.proxy.server=proxy.bercy.cp",AFTER);
    		ListAddString(listId,"xemelios.proxy.port=3128",AFTER);
	    	ListWriteToFile(listId,fileDir ^ fileName);
		endif;
	endif;
end;

function debug(msg)
begin
	//MessageBox(msg,INFORMATION);
end;

function NUMBER showInformationExit(msg)
NUMBER ret;
STRING data;
begin
	ret = SdShowDlgEdit1("Press Back to exit",msg, "Info",data);
	if(ret=BACK) then exit;
	endif;
	return ret;
end;
//---------------------------------------------------------------------------
// OnBegin
//
// The OnBegin event is called directly by the framework after the setup
// initializes.
//---------------------------------------------------------------------------
function OnBegin()   
	STRING DOCUMENT_DEFS_DIR, LIB_DIR, DOC_DIR;
	LONG ret;

begin
	LIB_DIR = INSTALLDIR ^ "Xemelios" ^ "root" ^ "lib";
	DOC_DIR = INSTALLDIR ^ "Xemelios" ^ "root" ^ "doc";
	DOCUMENT_DEFS_DIR = INSTALLDIR ^ "Xemelios" ^ "root" ^ "documents-def";

	// POE : On supprime tout le repertoire LIB_DIR
	ret = DeleteDir(LIB_DIR,ALLCONTENTS);
    
	// POE : On supprime tout le repertoire DOC_DIR
	ret = DeleteDir(DOC_DIR,ALLCONTENTS);          
	
	// POE : On supprime tout le repertoire DOCUMENT_DEFS_DIR
	ret = DeleteDir(DOCUMENT_DEFS_DIR,ALLCONTENTS);

	// CHM : on supprime le répertoire d'update par telechargement pour eviter le conflit entre les 2
	ret = DeleteDir(INSTALLDIR ^ "tmp-upd",ALLCONTENTS);
        
        // CHM : on supprime le components.xml qui doit etre mis a jour
        ret = DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "components.xml");

        // CHM : on supprime le import-batch.jar qui doit etre mis a jour
        ret = DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "import-batch.jar");

        // CHM : on supprime le xemelios.jar qui doit etre mis a jour
        ret = DeleteFile(INSTALLDIR ^ "Xemelios" ^ "root" ^ "xemelios.jar");
end;

#include "featureevents.rul"