'-----------------------------------------------------------------
' Flex EnvokeIT Logger Framework script
'-----------------------------------------------------------------
'
' AUTHOR: EnvokeIT Development Team
' DATE  : 2007-07-01

'
' COMMENT:
' This script is a copy of the original FlexFramework.vbs script 
' that NLLoginConsultants has made for the Flex Profile solution. 
'
' CHANGES:
' 2007-07-01	Richard Egenäs	Original Version
' 2007-09-20	Richard Egenäs	Added Do Loop that loops until the ops-file is created in the logoff part before continuing
'-------------------------------------------------------------------
'

On Error Resume Next

'*****************************************************************************************************************
' EnvokeIT Logger added section

    Dim g_strFlex_EnvokeIT_LogInfo
    Dim g_strScriptStartTime
    Dim g_strTimeCopyingINIFileAndReadingSettings
    Dim g_strLogFolder

    'Start script timer now
    g_strScriptStartTime = Timer()

' EnvokeIT Logger added section
'*****************************************************************************************************************

Set WshShell = WScript.CreateObject("WScript.Shell")
Set wshNetwork = WScript.CreateObject("WScript.Network")
Set ObjEnv = WshShell.Environment("Process")
Set WshArgs = WScript.Arguments
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set RegExObject = New RegExp 
With RegExObject 
        .Pattern = "%.+%" 
        .IgnoreCase = True 
        .Global = True 
End With 

OnOff = WshArgs.Item(0)
Flex_Config = WshArgs.Item(1)
Frameworkini = WshArgs.Item(2)

'Get Environment Variables
Servertype = WshShell.RegRead("HKLM\Software\Login Consultants\Flex Framework\ServerType")

Temp	= ObjEnv("TEMP")
UserDnsDomain = ObjEnv("USERDNSDOMAIN")
HomeDrive = ObjEnv("HOMEDRIVE")
HomePath = ObjEnv("HOMEPATH")
USERDOMAIN = ObjEnv("USERDOMAIN")
COMPUTERNAME = ObjEnv("COMPUTERNAME")
UserProfile = ObjEnv("USERPROFILE")
S4_EXE = ObjEnv("S4_EXE")

If UCase(OnOff) = "LOGON" Then
	If (ObjFSO.FileExists(USERPROFILE & "\FF_ERROR.txt")) Then
		ObjFSO.DeleteFile( USERPROFILE & "\FF_ERROR.txt" ), True
	End If
End If

If UCase(OnOff) = "LOGOFF" Then
	If (ObjFSO.FileExists(USERPROFILE & "\FF_ERROR.txt")) Then
		wscript.quit
	End If
End If

If not UCase(OnOff) = "LOGON" Then
	If not UCase(OnOff) = "LOGOFF" Then
		ProcessError ("FLEX ERROR: No LOGON or LOGOFF command found for Flex Framework")
	End If
End If

If Servertype = "" then
	ServerType	= ObjEnv("SERVERTYPE")
End If

'Set temporary folders
Temp_OPS = Temp & "\Temp_Ops"
Temp_INI = Temp & "\Temp_INI"

If Frameworkini = "" then
	FLEXINI = Flex_Config & "\Framework.ini"
Else
	FLEXINI = Frameworkini
End If

If ObjFSO.FileExists(FlexINI) Then
	ObjFSO.CopyFile FLEXINI, UserProfile & "\Flex_Set.INI", TRUE
	FLEXINI = UserProfile & "\Flex_Set.INI"
		Else
	ProcessError ("FLEX ERROR: Flex Framework Configuration file " & FLEXINI & " not found!")
End If

'Get settings from INI file
Refresh_Windows_Appearance = Readini(Flexini,"Main","Refresh_Windows_Appearance")
Refresh_Keyboard = Readini(Flexini,"Main","Refresh_Keyboard")
Refresh_Mouse = Readini(Flexini,"Main","Refresh_Mouse")
Enable_Passwords = Readini(Flexini,"Main","Enable_Passwords")
Enable_Certificates = Readini(Flexini,"Main","Enable_Certificates")
Compression = Readini(Flexini,"Main","Compression")
Compressionpriority = Readini(Flexini,"Main","Compression_priority")
Storeroot = Readini(Flexini,"Locations","Storeroot")
Storefolder = Readini(Flexini,"Locations","Storefolder")
Disable_Backup = Readini(Flexini,"Locations","Disable_Backup")
Display_Framework_Error = Readini(Flexini,"Errormessages","Display_Framework_Error")
Display_ProflWiz_Error = Readini(Flexini,"Errormessages","Display_ProflWiz_Error")

ProflwizOption= "/q"
If Display_ProflWiz_Error = "1" then 
	ProflwizOption= "/e"
End If
If Display_ProflWiz_Error = "2" then 
	ProflwizOption= "/p /e"
End If
If Display_ProflWiz_Error = "3" then 
	ProflwizOption= "/p"
End If


StoreRootConfig = StoreRoot

If Frameworkini = "" then
	Config = Flex_Config & "\ProfileSettings"
Else
	Config = Flex_Config
End If

Tools = WshShell.RegRead("HKLM\Software\Login Consultants\Flex Framework\InstallPath")

If Tools = "" then
	If not S4_EXE = "" then
		Tools	= S4_EXE & "\Flex Framework\Flex_EXE\"
	End If
End If

If Refresh_Windows_Appearance = "" Then 
	ProcessError ("FLEX ERROR: Setting Refresh_Windows_Appearance not found in " & FLEXINI)
End If
If Refresh_Keyboard = "" Then 
	ProcessError ("FLEX ERROR: Setting Refresh_Keyboard not found in " & FLEXINI)
End If
If Refresh_Mouse = "" Then 
	ProcessError ("FLEX ERROR: Setting Refresh_Mouse not found in " & FLEXINI)
End If
If Enable_Passwords = "" Then 
	ProcessError ("FLEX ERROR: Setting Enable_Passwords not found in " & FLEXINI)
End If
If Enable_Certificates = "" Then 
	ProcessError ("FLEX ERROR: Setting Enable_Certificates not found in " & FLEXINI)
End If
If Compression = "" Then 
	ProcessError ("FLEX ERROR: Setting Compression not found in " & FLEXINI)
End If
If Compression = "1" Then
	If Compressionpriority = "" Then 
		ProcessError ("FLEX ERROR: Setting Compression_priority not found in " & FLEXINI & "This Option is required, set it to: LOW, BELOWNORMAL, NORMAL, ABOVENORMAL or HIGH" )
	End If
End If
If Storeroot = "" Then 
	ProcessError ("FLEX ERROR: Setting Storeroot not found in " & FLEXINI)
End If
If Storefolder = "" Then 
	ProcessError ("FLEX ERROR: Setting Storefolder not found in " & FLEXINI)
End If
If Tools = "" Then 
	ProcessError ("FLEX ERROR: Setting HKLM\Software\Login Consultants\Flex Framework\InstallPath not found in the registry")
End If


StoreRoot = TransformVariables(StoreRoot)
Storefolder = TransformVariables(StoreFolder)


If not ObjFSO.FolderExists(Tools) Then
		ProcessError ("FLEX ERROR: The folder " & Tools & " cannot be found!")
		End If


If not ObjFSO.FolderExists(Config) Then
		ProcessError ("FLEX ERROR: The folder " & Config & " cannot be found!")
		End If


If StoreRoot = "1" Then
	StoreRoot = HomeDrive & HomePath
End If


'Check if NT4 domain or AD is used
If UserDnsDomain = "" Then
	AD = "0"
		Else
	AD = "1"
End If


'Check If Domain Query is needed
If Enable_Passwords = "1" Then
	GET_USER_INFO = "1"
End If
If	Enable_Certificates = "1" Then
	GET_USER_INFO = "1"
End If
If	StoreRoot = "2" Then
	GET_USER_INFO = "1"
End If
If	StoreRoot = "3" Then
	GET_USER_INFO = "1"
End If




If GET_USER_INFO = "1" Then
	If AD = "1" Then
		Set ObjADinfo = createobject("ADSystemInfo")
		strUserAdPath = ObjADinfo.userName
		Set objADObject = GetObject("LDAP://" & strUserAdPath)
		tempsid = objADobject.objectsid
		hexsid = OctetToHexStr(tempsid)
		decsid = HexStrToDecStr(hexsid)
		If	StoreRoot = "2" Then
			StoreRoot = objADobject.HomeDirectory
			If StoreRoot = "" Then
				ProcessError ("FLEX ERROR: There is no homedirectory found to save personal settings")	
			End If
		End If
		If	StoreRoot = "3" Then
			StoreRoot = objADobject.TerminalServicesHomeDirectory
			If StoreRoot = "" Then
				ProcessError ("FLEX ERROR: There is no Terminal Server Homedirectory found to save personal settings: this setting is only supported on Windows 2003 Server")	
			End If
		End If
	End If
	If AD = "0" Then
		strUserName = wshNetwork.userName
		strDomainName = wshNetwork.userDomain
		strUserAdPath = "WinNT://" & strDomainName & "/" & strUserName
		set objADObject = getobject( strUserAdPath )
		tempsid = objADobject.objectsid
		hexsid = OctetToHexStr(tempsid)
		decsid = HexStrToDecStr(hexsid)
		If	StoreRoot = "2" Then
			StoreRoot = objADobject.HomeDirectory
			If StoreRoot = "" Then
				ProcessError ("FLEX ERROR: There is no homedirectory found to save personal settings")
			End If
		End If
	End If
End If

'Change extension to 7z when compression is enabled
If COMPRESSION = "1" then
		EXTENSION="7z"
			Else
			EXTENSION="OPS"
End If

'Check if the Servertype variable is defined
If Servertype = "" Then
	Store = StoreRoot & "\" & StoreFolder
	Else
	Store = StoreRoot & "\" & StoreFolder & "\" & ServerType
	Config = Config & "\" & ServerType
End If

If not ObjFSO.FolderExists(store) Then
	GeneratePath Store
	
	If not ObjFSO.FolderExists(store) Then
		If UCase(OnOff) = "LOGON" Then
			If StoreRootConfig="1" then
				ProcessError ("FLEX ERROR: The location to save settings " & Store & " cannot be created. Mayby the permissions are not configured correctly. When the logon script is defined through GPO, chances are high that the Terminal Server Homedrive is not mapped yet when the logon script runs. To prevent these timing issues configure the logon script as a user property in the domain or add the logon script in the (HKLM\SOFTWARE\Microsoft\Windows NT\ CurrentVersion\Winlogon\Appsetup) registry key.")
			End If
		End If
		ProcessError ("FLEX ERROR: The location to save settings " & Store & " cannot be created.")
	End If
End If

'Create Temporary work folders
ObjFSO.DeleteFolder TEMP_OPS, True
ObjFSO.DeleteFolder TEMP_INI, True
ObjFSO.CreateFolder TEMP_OPS
ObjFSO.CreateFolder TEMP_INI


'*****************************************************************************************************************
' EnvokeIT Logger added section

    'Time spent gathering settings
    g_strTimeCopyingINIFileAndReadingSettings = vbNewLine & "Time spent on gathering Flex settings, Checking AD setting, and creating Temp folders etc; " & Round(Timer()-g_strScriptStartTime, 2) & " seconds"
    
' EnvokeIT Logger added section
'*****************************************************************************************************************

'*****************************************************************************************************************
' EnvokeIT Logger added section

    Call GatherServerAndSessionInfo()

    g_strFlex_EnvokeIT_LogInfo = g_strFlex_EnvokeIT_LogInfo & vbNewLine & g_strTimeCopyingINIFileAndReadingSettings

' EnvokeIT Logger added section
'*****************************************************************************************************************


'Copy INI Files for the Proflwiz in temp, only when the user has read permissions the files are copied
Set FolderName = ObjFSO.GetFolder(Config)
For Each Member in FolderName.Files
	'*****************************************************************************************************************
    ' EnvokeIT Logger added section
        
        Dim strINIFilesCopyStartTime
        Dim strINIFilesCopyStopTime
        
        strINIFilesCopyStartTime = Timer()
        
	    ObjFSO.CopyFile Config & "\" & Member.name, TEMP_INI & "\" & Member.name, True
        
        'Time spent copying INI-file
        g_strFlex_EnvokeIT_LogInfo = g_strFlex_EnvokeIT_LogInfo & vbNewLine & vbNewLine & "Time spent copying config file; " & Config & "\" & Member.name & ": " & Round(Timer()-strINIFilesCopyStartTime, 2) & " seconds"

        
    ' EnvokeIT Logger added section
    '*****************************************************************************************************************
Next

'Execute when logon
If UCase(OnOff) = "LOGON" Then
	'Set the profile state to roaming to enable certificates
	If ENABLE_CERTIFICATES="1" Then
		WshShell.RegWrite "HKLM\Software\Microsoft\Windows NT\Currentversion\Profilelist\" & decsid & "\STATE",256,"REG_DWORD"
	End If
	
	'Copy (compressed) ops files in working folder when the corresponding INI file exist in TEMP_INI
	'Then run for each ops file the proflwiz.exe
	Set FolderName = ObjFSO.GetFolder(TEMP_INI)
	For Each Member in FolderName.Files
		
		'*****************************************************************************************************************
        ' EnvokeIT Logger added section
            
            Dim strLogonSettingFilesStartTime
            
            strLogonSettingFilesStartTime = Timer()

        ' EnvokeIT Logger added section
        '*****************************************************************************************************************     
        
		File_Name = ObjFSO.GetBaseName(Member)
		If ObjFSO.FileExists(Store & "\" & File_Name & "." & EXTENSION ) Then
  			If Compression = "1" Then
 	 			Wshshell.Run "cmd /c Start " & Chr(34) & "DECOMPRESSING SETTINGS" & Chr(34) & " /D" & Chr(34) & TEMP_OPS & Chr(34) & " /MIN /WAIT /" & COMPRESSIONPRIORITY & " " & chr(34) & TOOLS & "7z.exe" & chr(34) & " e -tz7 " & chr(34) &  Store & "\" & File_Name & "." & EXTENSION & chr(34), 0, true
  			Else
  				ObjFSO.CopyFile Store & "\" & File_Name & "." & EXTENSION, TEMP_OPS & "\", true
  			End If
  			If ObjFSO.FileExists(TEMP_OPS & "\" & File_Name & ".ops")	Then
  				Wshshell.Run Chr(34) & TOOLS & "proflwiz.exe" & Chr(34) & " /r " & Chr(34) & TEMP_OPS & "\" & File_Name & "." & "ops" & Chr(34) & " " & ProflwizOption , 0, true
			End If
		End If
				
		If NOT ObjFSO.FileExists(Store & "\" & File_Name & "." & EXTENSION ) Then
			If ObjFSO.FileExists(Store & "\" & File_Name & ".7z") Then
 	 			Wshshell.Run "cmd /c Start " & Chr(34) & "DECOMPRESSING SETTINGS" & Chr(34) & " /D" & Chr(34) & TEMP_OPS & Chr(34) & " /MIN /WAIT /" & COMPRESSIONPRIORITY & " " & chr(34) & TOOLS & "7z.exe" & chr(34) & " e -tz7 " & chr(34) &  Store & "\" & File_Name & ".7z" & chr(34), 0, true
  			End If
  			If ObjFSO.FileExists(Store & "\" & File_Name & ".ops") Then
  				ObjFSO.CopyFile Store & "\" & File_Name & ".ops", TEMP_OPS & "\", true
  			End If
  			If ObjFSO.FileExists(TEMP_OPS & "\" & File_Name & ".ops")	Then
  				Wshshell.Run Chr(34) & TOOLS & "proflwiz.exe" & Chr(34) & " /r " & Chr(34) & TEMP_OPS & "\" & File_Name & "." & "ops" & Chr(34) & " " & ProflwizOption , 0, true
			End If	
  		End If
  		
  		'*****************************************************************************************************************
        ' EnvokeIT Logger added section
           
  		    'Time spent copying INI-file
            g_strFlex_EnvokeIT_LogInfo = g_strFlex_EnvokeIT_LogInfo & vbNewLine & vbNewLine & "Time spent restoring setting file; " & TEMP_OPS & "\" & File_Name & ".ops: " & Round(Timer()-strLogonSettingFilesStartTime, 2) & " seconds"
            
	    ' EnvokeIT Logger added section
        '***************************************************************************************************************** 
  	Next

	'This code snippet is gracefully suplied by NeilH
	strMUILangID = UCase(WshShell.RegRead("HKCU\Control Panel\Desktop\MultiUILanguageID"))
	strMUILangPending = UCase(WshShell.RegRead("HKCU\Control Panel\Desktop\MUILanguagePending"))
	If strMUILangPending <> "" Then
  	If strMUILangID <> strMUILangPending Then
  'Need to set the correct MultiUILanguageID in the registry
			WshShell.RegWrite "HKCU\Control Panel\Desktop\MultiUILanguageID", strMUILangPending, "REG_SZ"
		End If
	End If
	
	'*****************************************************************************************************************
    ' EnvokeIT Logger added section
            
            Dim strFlexResfreshStartTime
            
            strFlexResfreshStartTime = Timer()
            
    ' EnvokeIT Logger added section
    '*****************************************************************************************************************

	'Run FlexRefresh
	If REFRESH_WINDOWS_APPEARANCE="1" Then
		Run = WshShell.Run(Chr(34) & TOOLS & "FlexRefresh.exe" & Chr(34), 0, false)
	End If
	'Enable Password by precreating the SID in the registry
	If  ENABLE_PASSWORDS="1" Then
		WshShell.RegWrite "HKCU\Software\Microsoft\Protected Storage System Provider\" & decsid & "\temp" ,"temp"
		WshShell.RegDelete "HKCU\Software\Microsoft\Protected Storage System Provider\" & decsid & "\temp"
	End If
	'Refresh Keyboard and Mouse settings
	If REFRESH_KEYBOARD="1" Then
		Preload = WshShell.RegRead("HKCU\Keyboard Layout\Preload\1")
		Substitute = WshShell.RegRead("HKCU\Keyboard Layout\Substitutes\" & Preload)
		If Substitute = "" then
     	Run = WshShell.run(Chr(34) & TOOLS & "Setlocale.exe" & Chr(34) & " 0000" & right(Preload,4) & " " & "0000" & right(Preload,4), 0, True)
		Else
     	Run = WshShell.run(Chr(34) & TOOLS & "Setlocale.exe" & Chr(34) & " 0000" & right(Preload,4) & " " & Substitute, 0, True)
		End If
	End If
		If REFRESH_MOUSE="1" Then
  	If WshShell.RegRead("HKCU\Control Panel\Mouse\SwapMouseButtons") = 1 then
      Run = WshShell.run("rundll32 user32.dll,SwapMouseButton", 0, True)
   	End If
	End If
	'General Refresh of system settings
	Wshshell.Run "RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True", 0, false
	
	'*****************************************************************************************************************
    ' EnvokeIT Logger added section
       
	    'Time spent running FlexResfresh and general system sessions refresh
        g_strFlex_EnvokeIT_LogInfo = g_strFlex_EnvokeIT_LogInfo & vbNewLine & vbNewLine & "Time spent running FlexRefresh and general system settings refresh; " & Round(Timer()-strFlexResfreshStartTime, 2) & " seconds"
        
    ' EnvokeIT Logger added section
    '*****************************************************************************************************************   
    
End If  'End LOGON Execution


'Execute when logoff
If UCase(OnOff) = "LOGOFF" Then
	Set FolderName = ObjFSO.GetFolder(TEMP_INI)
	BackupFolder = Store & "\Settings_Backup"

	'Remove redundant OPS files
	Set CheckFolder = ObjFSO.GetFolder(Store)
	For Each Filer in Checkfolder.Files
		File2 = ObjFSO.GetBaseName(Filer)
		If Not ObjFSO.FileExists(TEMP_INI & "\" & File2 & ".INI") Then
			ObjFSO.DeleteFile(Filer), true
		End If
	Next
	Set CheckFolder = ObjFSO.GetFolder(BackupFolder)
	For Each Filer in Checkfolder.Files
		File2 = ObjFSO.GetBaseName(Filer)
		If Not ObjFSO.FileExists(TEMP_INI & "\" & File2 & ".INI") Then
			ObjFSO.DeleteFile(Filer), true
		End If
	Next
	 
	If Disable_Backup="1" Then
		ObjFSO.DeleteFolder BackupFolder, True
	Else
		ObjFSO.CreateFolder BackupFolder
	End If
	For Each Member in FolderName.Files
		'*****************************************************************************************************************
        ' EnvokeIT Logger added section
            
            Dim strLogoffSettingFilesStartTime
            
            strLogoffSettingFilesStartTime = Timer()
            
	    ' EnvokeIT Logger added section
        '*****************************************************************************************************************
        
		File_Name = ObjFSO.GetBaseName(Member)
 		Wshshell.Run Chr(34) & TOOLS & "proflwiz.exe" & Chr(34) & " /s " & Chr(34) & TEMP_OPS & "\" & File_Name & "." & "ops" & Chr(34) & " /i " & TEMP_INI & "\" & File_Name & "." & "ini " & ProflwizOption , 0, true
		'Sometimes the proflwiz.exe task above isn't completed when the script continues and therefore we loop until we verify that the file is there.. 
		Do Until ObjFSO.FileExists(TEMP_OPS & "\" & File_Name & ".ops")
			'wait
			Wscript.Sleep 100
		Loop
		If ObjFSO.FileExists(TEMP_OPS & "\" & File_Name & ".ops") Then
			If Not Disable_Backup="1" Then
				If ObjFSO.FileExists(Backupfolder & "\" & File_Name & "." & EXTENSION) Then
					ObjFSO.DeleteFile(Backupfolder & "\" & File_Name & "." & EXTENSION), true
				End If			
				PreviousFile = Store & "\" & File_Name & "." & EXTENSION
				If ObjFSO.FileExists(PreviousFile) Then
					BackupFile = Backupfolder & "\" & File_Name & "." & EXTENSION
					ObjFSO.MoveFile PreviousFile, BackupFile
				End If
			End If
			If Compression = "1" Then
 	 			Wshshell.Run "cmd /c Start " & Chr(34) & "COMPRESSING SETTINGS" & Chr(34) & " /D" & Chr(34) & TEMP_OPS & Chr(34) & " /MIN /WAIT /" & COMPRESSIONPRIORITY & " " & chr(34) & TOOLS & "7z.exe" & chr(34) & " a -t7z " & chr(34) &  Store & "\" & File_Name & "." & EXTENSION & chr(34) & " " & File_Name & ".ops -mx=1", 0, true
  		Else
  			ObjFSO.CopyFile  TEMP_OPS & "\" & File_Name & "." & EXTENSION, Store & "\", true
  		End If
		End If
		
		'*****************************************************************************************************************
        ' EnvokeIT Logger added section
           
  		    'Time spent copying INI-file
            g_strFlex_EnvokeIT_LogInfo = g_strFlex_EnvokeIT_LogInfo & vbNewLine & vbNewLine & "Time spent exporting and copying configuration file; " & TEMP_OPS & "\" & File_Name & ".ops: " & Round(Timer()-strLogoffSettingFilesStartTime, 2) & " seconds"
            
	    ' EnvokeIT Logger added section
        '*****************************************************************************************************************  
        
	Next
	'Set the profile state to roaming to enable certificates
	If ENABLE_CERTIFICATES="1" Then
		WshShell.RegWrite "HKLM\Software\Microsoft\Windows NT\Currentversion\Profilelist\" & decsid & "\STATE",133,"REG_DWORD"
	End If
End If 		'End LOGOFF Execution

'*****************************************************************************************************************
' EnvokeIT Logger added section
    
    Dim strDelTempFilesStartTime
    
    strDelTempFilesStartTime = Timer()
    
' EnvokeIT Logger added section
'*****************************************************************************************************************

'Cleanup temporary Files
ObjFSO.DeleteFolder TEMP_OPS, True
ObjFSO.DeleteFolder TEMP_INI, True
ObjFSO.DeleteFile FLEXINI, True

'*****************************************************************************************************************
' EnvokeIT Logger added section
   
    'Time deleting temp files..
    g_strFlex_EnvokeIT_LogInfo = g_strFlex_EnvokeIT_LogInfo & vbNewLine & vbNewLine & "Time spent deleting temporary files and folders; " & Round(Timer()-strDelTempFilesStartTime, 2) & " seconds"
    
    'Add total duration of script to the log...
    g_strFlex_EnvokeIT_LogInfo = g_strFlex_EnvokeIT_LogInfo & vbNewLine & vbNewLine & "Total time spent running the script; " & Round(Timer()-g_strScriptStartTime, 2) & " seconds"
    
    'Write to the logfile!! 
    WriteToLogFile UCase(OnOff)
    
' EnvokeIT Logger added section
'*****************************************************************************************************************        

'-------------------------------------------------------------------------------------------------
'------------------------------------------Functions----------------------------------------------
'-------------------------------------------------------------------------------------------------

Function ReadIni(file, section, item)
  ReadIni = ""
  file = Trim(file)
  item = Trim(item)
  If ObjFSO.FileExists( file ) Then
    Set ini = ObjFSO.OpenTextFile( file, 1, False)
    Do While ini.AtEndOfStream = False
      line = ini.ReadLine
      line = Trim(line)
      If LCase(line) = "[" & LCase(section) & "]" Then
        line = ini.ReadLine
        line = Trim(line)
        Do While Left( line, 1) <> "["
          'If InStr( 1, line, item & "=", 1) = 1 Then
          equalpos = InStr(1, line, "=", 1 )
          If equalpos > 0 Then
            leftstring = Left(line, equalpos - 1 )
            leftstring = Trim(leftstring)
            If LCase(leftstring) = LCase(item) Then
              ReadIni = Mid( line, equalpos + 1 )
              ReadIni = Trim(ReadIni)
              Exit Do
            End If
          End If
          If ini.AtEndOfStream Then Exit Do
          line = ini.ReadLine
          line = Trim(line)
        Loop
        Exit Do
      End If
    Loop
    ini.Close
  End If
End Function



Function OctetToHexStr(arrbytOctet)
' Function to convert OctetString (byte array) to Hex string.
dim st
  Dim k
  OctetToHexStr = ""
  For k = 1 To Lenb(arrbytOctet)
    OctetToHexStr = OctetToHexStr _
      & Right("0" & Hex(Ascb(Midb(arrbytOctet, k, 1))), 2)
  Next
End Function


Function HexStrToDecStr(strSid)
  Dim arrbytSid, lngTemp, j

  ReDim arrbytSid(Len(strSid)/2 - 1)

  For j = 0 To UBound(arrbytSid)
    arrbytSid(j) = CInt("&H" & Mid(strSid, 2*j + 1, 2))
  Next

  HexStrToDecStr = "S-" & arrbytSid(0) & "-" _
    & arrbytSid(1) & "-" & arrbytSid(8)

  lngTemp = arrbytSid(15)
  lngTemp = lngTemp * 256 + arrbytSid(14)
  lngTemp = lngTemp * 256 + arrbytSid(13)
  lngTemp = lngTemp * 256 + arrbytSid(12)

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)

  lngTemp = arrbytSid(19)
  lngTemp = lngTemp * 256 + arrbytSid(18)
  lngTemp = lngTemp * 256 + arrbytSid(17)
  lngTemp = lngTemp * 256 + arrbytSid(16)

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)

  lngTemp = arrbytSid(23)
  lngTemp = lngTemp * 256 + arrbytSid(22)
  lngTemp = lngTemp * 256 + arrbytSid(21)
  lngTemp = lngTemp * 256 + arrbytSid(20)

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)

  lngTemp = arrbytSid(27)
  lngTemp = lngTemp * 256 + arrbytSid(26)
  lngTemp = lngTemp * 256 + arrbytSid(25)
  lngTemp = lngTemp * 256 + arrbytSid(24)

  HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)


End Function

Function GeneratePath(pFolderPath) 
    GeneratePath = False 
    If Not objFSO.FolderExists(pFolderPath) Then 
        If GeneratePath(objFSO.GetParentFolderName(pFolderPath)) Then 
            GeneratePath = True 
            Call objFSO.CreateFolder(pFolderPath) 
        End If 
    Else 
        GeneratePath = True 
    End If 
End Function

Function ProcessError(ErrorType)
	Set ErrorFile = objfso.OpenTextFile( USERPROFILE & "\FF_ERROR.txt", 2 , True)
	ErrorFile.WriteLine(ErrorType)
	ErrorFile.Close
 Wscript.echo(ErrorType)
	If Display_Framework_Error = "1" Then
			If UCase(OnOff) = "LOGON" Then
				MsgBox (ErrorType)
			End If
	End If
	If Display_Framework_Error = "2" Then
				MsgBox (ErrorType)
	End If
	Wscript.quit
End Function



Function TransformVariables(strLine)
Set expMatch = RegExObject.Execute(strLine) 
If expMatch.Count > 0 Then
  For Each expressionMatched in expMatch
    strLine = Replace(strLine, expressionmatched.Value, WshShell.ExpandEnvironmentStrings(expressionmatched.Value))
  Next
End If
TransformVariables = strLine
End Function

'*****************************************************************************************************************
' EnvokeIT Logger added section

'***********************************************************************************
'
' Function added by EnvokeIT 2006-07-15
' for more information see the Flex EnvokeIT Logger guide available at:
' http://www.envokeit.com/downloads/Scripts/Flex_EnvokeIT_Logger_Framework.zip
'
'***********************************************************************************
Private Sub GatherServerAndSessionInfo()
    Dim objWSHShell
    Dim strStartGatherTime
    
    strStartGatherTime = Timer()
    
    Err.Clear
    Set objWSHShell = Wscript.CreateObject("Wscript.Shell")
    
    If Err.number = 0 Then
        g_strFlex_EnvokeIT_LogInfo = "*******************************************************************************************************" & vbNewLine _
            & "Date:" & vbTab & Date & vbNewLine _
            & "Time:" & vbTab & Time & vbNewLine _
            & "Server:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%COMPUTERNAME%") & vbNewLine _
            & "HOMEDRIVEHOMEPATH:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%HOMEDRIVE%%HOMEPATH%") & vbNewLine _
            & "TEMP:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%TEMP%") & vbNewLine _
            & "SESSIONNAME:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%SESSIONNAME%") & vbNewLine _
            & "LOGONSERVER:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%LOGONSERVER%") & vbNewLine _
            & "USERDOMAIN:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%USERDOMAIN%") & vbNewLine _
            & "USERNAME:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%USERNAME%") & vbNewLine _
            & "USERPROFILE:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%USERPROFILE%") & vbNewLine _
            & "APPDATA:" & vbTab & objWSHShell.ExpandEnvironmentStrings("%APPDATA%") & vbNewLine _
            & "DESKTOP:" & vbTab & objWSHShell.SpecialFolders("Desktop") & vbNewLine _
            & "Favorites:" & vbTab & objWSHShell.SpecialFolders("Favorites") & vbNewLine _
            & "MyDocuments:" & vbTab & objWSHShell.SpecialFolders("MyDocuments") & vbNewLine _
            & "StartMenu:" & vbTab & objWSHShell.SpecialFolders("StartMenu") & vbNewLine _
            & vbNewLine & vbNewLine & "---- FLEX Settings ----" & vbNewLine _
            & "Refresh_Windows_Appearance:" & vbTab & Refresh_Windows_Appearance & vbNewLine _
            & "Refresh_Keyboard:" & vbTab & Refresh_Keyboard & vbNewLine _
            & "Refresh_Mouse:" & vbTab & Refresh_Mouse & vbNewLine _
            & "Enable_Passwords:" & vbTab & Enable_Passwords & vbNewLine _
            & "Enable_Certificates:" & vbTab & Enable_Certificates & vbNewLine _
            & "Compression:" & vbTab & Compression & vbNewLine _
            & "Compressionpriority:" & vbTab & Compressionpriority & vbNewLine _
            & "Storeroot:" & vbTab & Storeroot & vbNewLine _
            & "Storefolder:" & vbTab & Storefolder & vbNewLine _
            & "Disable_Backup:" & vbTab & Disable_Backup & vbNewLine _
            & "Display_Framework_Error:" & vbTab & Display_Framework_Error & vbNewLine _
            & "Display_ProflWiz_Error:" & vbTab & Display_ProflWiz_Error & vbNewLine _
            & "Config:" & vbTab & Config & vbNewLine & vbNewLine & vbNewLine & "Time spent gathering session information: " & Round(Timer()-strStartGatherTime, 2) & " seconds"
            
           
    End If
    
    Set objWSHShell = Nothing
    
End Sub

'***********************************************************************************
'
' Function added by EnvokeIT 2006-07-15
' for more information see the Flex EnvokeIT Logger guide available at:
' http://www.envokeit.com/downloads/Scripts/Flex_EnvokeIT_Logger_Framework.zip
'
'***********************************************************************************
Private Sub WriteToLogFile(strLogonOrLogoff)
	
	Dim objFSO
	Dim objLogfile
	Dim strLogFile
	Dim intNumberOfLogfilesToKeep
	
	Set objFSO = Wscript.CreateObject("Scripting.FileSystemObject")
	
	'Change this path if you don't like to store the log files in the users Storeroot folder configured in Framework.ini, it's perfectly ok to use paths like; \\SERVERNAME\USERLOGS_SHARE\%USERNAME%\Logs paths, just remember to ExpandEnvironmentStrings like this if you like to use variables; WSHShell.ExpandEnvironmentStrings("\\SERVERNAME\USERLOGS_SHARE\%USERNAME%\Logs") 
	g_strLogFolder = Storeroot & "\" & Storefolder & "\Logs"
	
	If Not objFSO.FolderExists(g_strLogFolder) Then
	    objFSO.CreateFolder g_strLogFolder
	End If
	
	'Change this to the number of logon and logoff logs you want to store for each user, for example; 9 will store 10 logon and 10 logoff files, 19 will store 20 logon and logoff files
	intNumberOfLogfilesToKeep = 9
	
	If strLogonOrLogoff = "LOGON" Then
		strLogFile = "Logon"
	ElseIf strLogonOrLogoff = "LOGOFF" Then
		strLogFile = "Logoff"
	End If
	
	Dim intCount
	
	intCount = 0
	
	Do While intCount <= intNumberOfLogfilesToKeep 
		If objFSO.FileExists(g_strLogFolder & "\" & strLogFile & intNumberOfLogfilesToKeep - intCount & ".log") Then
			If objFSO.FileExists(g_strLogFolder & "\" & strLogFile & (intNumberOfLogfilesToKeep - intCount)+1 & ".log") Then
				objFSO.DeleteFile g_strLogFolder & "\" & strLogFile & (intNumberOfLogfilesToKeep - intCount)+1 & ".log"
			End If
			
			objFSO.MoveFile g_strLogFolder & "\" & strLogFile & intNumberOfLogfilesToKeep - intCount & ".log", g_strLogFolder & "\" & strLogFile & (intNumberOfLogfilesToKeep - intCount)+1 & ".log"
		End If
		intCount = intCount + 1
	Loop
	
	Set objLogFile = objFSO.OpenTextFile(g_strLogFolder & "\" & strLogFile & "1.log", 8, true)

	objLogFile.WriteLine g_strFlex_EnvokeIT_LogInfo

	objLogFile.Close

	Set objFSO = Nothing
	On error resume next
End Sub
' EnvokeIT Logger added section
'*****************************************************************************************************************

