Option Explicit

'------------------------------------------------------------------------------
' Constants
'------------------------------------------------------------------------------
Const FORREADING   = 1 ' Open a file for reading only. You can't write to this file.
Const FORWRITING   = 2 ' Open a file for writing only. You can't read from this file.
Const FORAPPENDING = 8 ' Open a file and write to the end of the file.
Const HKCR         = &H80000000 'HKEY_CLASSES_ROOT
Const HKLM         = &H80000002 'HKEY_LOCAL_MACHINE
Const HKU          = &H80000003 'HKEY_USERS
Const Success = 0
Const Failure = 1
Const LogTypeInfo = 1
Const LogTypeWarning = 2
Const LogTypeError = 3
Const TextCompare = 1

'------------------------------------------------------------------------------
' Global Common Objects
'------------------------------------------------------------------------------
Dim oFSO,oWshShell,oReg,cArgs,oEnv,oNet

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oWshShell = WScript.CreateObject("WScript.Shell")
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\./root/default:StdRegProv")
Set cArgs = Wscript.Arguments
Set oEnv = oWshShell.Environment("PROCESS")
Set oNet = WScript.CreateObject("WScript.Network")

'------------------------------------------------------------------------------
' Global Common Variables
'------------------------------------------------------------------------------
Dim CurrentScriptFolder,sLogFile,LogFile,sBaseKey,sCommonDesktop,sCommonStartMenu,sCommonPrograms,sCommonStartup,ErrorCode,CurMonth,CurDay,sCurrentVersion,sOSType,sLanguage,iA2D

CurrentScriptFolder = Left(Wscript.ScriptFullName, Len(Wscript.ScriptFullName) - Len(Wscript.ScriptName))
LogFile = oNet.ComputerName
sLogFile = "M:\Logs\" & LogFile & ".log"
sBaseKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
ErrorCode = oReg.GetExpandedStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", "Common Desktop", sCommonDesktop)
ErrorCode = oReg.GetExpandedStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", "Common Start Menu", sCommonStartMenu)
ErrorCode = oReg.GetExpandedStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", "Common Programs", sCommonPrograms)
ErrorCode = oReg.GetExpandedStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", "Common Startup", sCommonStartup)
ErrorCode = oReg.GetExpandedStringValue(HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentVersion", sCurrentVersion)
sOSType = "Other"
If sCurrentVersion = "5.1" Then sOSType = "XP"
If sCurrentVersion = "6.0" Then sOSType = "Vista"
oEnv("SEE_MASK_NOZONECHECKS") = 1
ErrorCode = 0

'------------------------------------------------------------------------------
' Global Specific Objects and Variables
'------------------------------------------------------------------------------
Dim oWMI
Dim sThisScriptName,sThisScriptDir,bDebug
Dim sExchangeServer,sWebmailServer,sDefaultLanguage,sTimezone,sVolumeLicenseKey,sVolumeLicenseKeyTabletPC,sFullName,sOrgName,sDomain,sDomainAccount,sDomainpassword,sLocalAdminPassword,sAdminGroups,sRemoteAssistanceGroups
Dim sComputerName,aMasterImage,sMasterImage,sMasterImageType,sProfileType
Dim sAssetTag, sSerialNumber, sMake, sModel, sModel2, sProduct, sUUID, bIsLaptop, bIsDesktop, bIsServer
Dim sIPAddress, sMacAddress, sDefaultGateway
Dim sDriverPath
Set oWMI = GetObject("winmgmts:")

sThisScriptName = Wscript.ScriptName
sThisScriptDir = oFSO.GetParentFolderName(WScript.ScriptFullName)

'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Main Part
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
On Error Resume Next

If oFSO.FileExists(CurrentScriptFolder & "Deploy.ini") Then
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "ExchangeServer",sExchangeServer)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "WebmailServer",sWebmailServer)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "DefaultProfile",sProfileType)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "DefaultLanguage",sDefaultLanguage)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "Timezone",sTimezone)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "VolumeLicenseKey",sVolumeLicenseKey)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "VolumeLicenseKeyTabletPC",sVolumeLicenseKeyTabletPC)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "FullName",sFullName)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "OrgName",sOrgName)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "Domain",sDomain)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "DomainAccount",sDomainAccount)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "Domainpassword",sDomainpassword)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "LocalAdminPassword",sLocalAdminPassword)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "AdminGroups",sAdminGroups)
	ErrorCode = GetIniValue(CurrentScriptFolder & "Deploy.ini", "DEPLOY", "RemoteAssistanceGroups",sRemoteAssistanceGroups)
Else
	Wscript.Quit
End If


LogInfo sLogFile, "------ Getting informations ------", LogTypeInfo

ErrorCode = GetAssetInfoByWMI(sSerialNumber, sMake, sModel, bIsLaptop, bIsDesktop, bIsServer)
sModel2 = GetModelPath(sMake, sModel)
ErrorCode = GetIniValue(CurrentScriptFolder & "Images\ComputerMapping.ini", sMake, sModel ,sMasterImage)

If not (oWMI is Nothing) then
	ErrorCode = GetNetworkInfoByWMI(sIPAddress, sMacAddress, sDefaultGateway)
ElseIf (sOSVersion = "NT" or sOSVersion = "WinPE") then
	ErrorCode = GetNetworkInfoForNT(dicIPAddresses, dicMacAddresses, dicDefaultGateways)
ElseIf (sOSVersion = "98") then
	ErrorCode = GetNetworkInfoFor98(dicIPAddresses, dicMacAddresses, dicDefaultGateways)
Else
	LogInfo sLogFile, "Invalid OS. No further processing", LogTypeError
	iRetVal = Failure
End if

'***********************  User interface   **************************
'Setting Default Values ( based on html control names)
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\ASK-UI_DisplayMode","NORMAL"
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\ASK-UI_WIDTH","625"
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\ASK-UI_HEIGHT","600"
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\ASK-UI_BTN1","Begin Deployment"
If sModel2 <> "" Then oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\Model",sModel2
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\MasterImage",sMasterImage
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\ProfileType",sProfileType
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\ExchangeServer",sExchangeServer
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\WebmailServer",sWebmailServer
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\DefaultLanguage",sDefaultLanguage
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\Timezone",sTimezone
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\VolumeLicenseKey",sVolumeLicenseKey
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\VolumeLicenseKeyTabletPC",sVolumeLicenseKeyTabletPC
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\FullName",sFullName
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\OrgName",sOrgName
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\Domain",sDomain
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\DomainAccount",sDomainAccount
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\AdminGroups",sAdminGroups
oWshShell.RegWrite "HKCU\SOFTWARE\HTA-UI\RemoteAssistanceGroups",sRemoteAssistanceGroups


'Calling HTA user interface
HTAEXEC CurrentScriptFolder & "Deploy.html"
If oWshShell.Regread("HKCU\SOFTWARE\HTA-UI\UI_BTN") = "Begin Deployment" Then
	sComputerName = oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\ComputerName")
	sModel = oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\Model")
	aMasterImage = Split(oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\MasterImage"),",")
	sMasterImage = aMasterImage(0)
	sMasterImageType = aMasterImage(1)
	sProfileType = oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\ProfileType")
	sDefaultLanguage = oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\DefaultLanguage")
	sExchangeServer = oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\ExchangeServer")
	sWebmailServer = oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\WebmailServer")
	sTimezone = oWshShell.Regread ("HKCU\SOFTWARE\HTA-UI\Timezone")
	
	If sComputerName <> "" Then
		If oFSO.FileExists("M:\Logs\" & sComputerName & ".log") Then oFSO.DeleteFile "M:\Logs\" & sComputerName & ".log",True
		ErrorCode = CopyLogFile(sLogFile,"M:\Logs\" & sComputerName & ".log")
		sLogFile = "M:\Logs\" & sComputerName & ".log"
	Else
		If oFSO.FileExists(sLogFile) Then oFSO.DeleteFile sLogFile,True
		oWshShell.RegDelete "HKCU\SOFTWARE\HTA-UI\"
		Wscript.Quit
	End If
	oWshShell.RegDelete "HKCU\SOFTWARE\HTA-UI\"
	
	'////////////////////////////////////////////////////////////////////////////
	'// Display Splash Screen
	'////////////////////////////////////////////////////////////////////////////
	oWshShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\SplashMsg\CurrentDisplayText", "Master Deployment, Please wait ..."
	oWshShell.Run  "mshta.exe " & CurrentScriptFolder & "splashMsg.hta",0,False
	
	LogInfo sLogFile, "------ PreInstall Phase ------", LogTypeInfo
	ErrorCode = PreInstall
	If ErrorCode = 0 Then
		LogInfo sLogFile, "PreInstall Phase finished", LogTypeInfo
	Else
		LogInfo sLogFile, "Error during PreInstall Phase", LogTypeError
		SplashMsg "EXIT"
		wscript.quit ErrorCode
	End If

	LogInfo sLogFile, "------ Deploying Phase ------", LogTypeInfo
	ErrorCode = Deploy(sMasterImage)
	If ErrorCode = 0 Then
		LogInfo sLogFile, "Deploying Phase finished", LogTypeInfo
	Else
		LogInfo sLogFile, "Error during Deploying Phase", LogTypeError
		SplashMsg "EXIT"
		wscript.quit ErrorCode
	End If
	
	LogInfo sLogFile, "------ PostInstall Phase ------", LogTypeInfo
	ErrorCode = PostInstall()
	If ErrorCode = 0 Then
		LogInfo sLogFile, "PostInstall Phase finished", LogTypeInfo
	Else
		LogInfo sLogFile, "Error during PostInstall Phase", LogTypeError
		SplashMsg "EXIT"
		wscript.quit ErrorCode
	End If
	SplashMsg "EXIT"
Else
	oWshShell.RegDelete "HKCU\SOFTWARE\HTA-UI\"
End If

'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' End of Main Part
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------

Function GetModelPath(sMake, sModel)
	Dim SubFolder,SubFolder2
	GetModelPath = ""
	
	For Each SubFolder in oFSO.GetFolder("M:\Drivers").SubFolders
		If InStr(1,UCase(sMake),UCase(SubFolder.Name),1) <> 0 Then
			sMake = SubFolder.Name
			For Each SubFolder2 in oFSO.GetFolder(SubFolder.Path).SubFolders
				If InStr(1,UCase(sModel),UCase(SubFolder2.Name),1) <> 0 Then
					sModel = SubFolder2.Name
					GetModelPath = SubFolder2.Path
				End If
			Next
		End If
	Next
End Function

Function Preinstall()
	Dim iRetVal
	SplashMsg "------ PreInstall Phase ------"
	SplashMsg2 "Running Diskpart"
	LogInfo sLogFile, "About to run Diskpart...", LogTypeInfo
	iRetVal = oWshShell.Run("DISKPART.EXE /s ""M:\Diskpart.txt""", 0, true)
	If iRetVal <> Success Then
		LogInfo sLogFile, "ERROR - Diskpart returned a non-zero return code, rc = " & iRetVal, LogTypeError
		Preinstall = iRetVal
		EXIT Function
	End If
	
	LogInfo sLogFile, "Diskpart finished...", LogTypeInfo
	' Wait a few seconds
	WScript.Sleep 5000
		' Now run a quick format for c:
		SplashMsg2 "Formatting c:"
	LogInfo sLogFile, "About to run quick format for C:...", LogTypeInfo
	iRetVal = oWshShell.Run("FORMAT C: /FS:NTFS /V:SYSTEM /Q /Y", 0, true)
	If iRetVal <> Success Then
		LogInfo sLogFile, "ERROR - Quick format returned a non-zero return code during format of C:, rc = " & iRetVal, LogTypeError
		Preinstall = iRetVal
		EXIT Function
	End If
	LogInfo sLogFile, "Diskpart Ok and C: formated.", LogTypeInfo
End Function

Function Deploy(ImageName)
	Dim iRetVal
	SplashMsg "------ Deploying Phase ------"
	SplashMsg2 "Running ImageX"
	LogInfo sLogFile, "About to run Imagex with the following command : M:\Images\Imagex.exe /apply M:\Images\" & ImageName & ".wim 1 c:", LogTypeInfo
	iRetVal = oWshShell.Run("M:\Images\Imagex.exe /apply M:\Images\" & ImageName & ".wim 1 c:", 0, true)
	If iRetVal <> Success Then
		LogInfo sLogFile, "ERROR - imagex returned a non-zero return code during deployment, rc = " & iRetVal, LogTypeError
		Deploy = iRetVal
		EXIT Function
	End If
	LogInfo sLogFile, "Image Deployment finished", LogTypeInfo
End Function

Function PostInstall()
	Dim oCmdLinesFile,oInstallFile,oSetRegOptsFile
	SplashMsg "------ PostInstall Phase ------"
	ErrorCode = CopyDrivers(sModel)
	ErrorCode = UpdateSysprepInf("C:\Sysprep\Sysprep.inf")
	ErrorCode = UpdateDevicePath()
	ErrorCode = UpdateSequencer(sMasterImage,sProfileType)
	
	SplashMsg2 "Language Configuration"
	LogInfo sLogFile, "------ Configuration of the language ------", LogTypeInfo
	If oFSO.FolderExists("M:\Language\" & sDefaultLanguage) Then
		LogInfo sLogFile, "Configuring " & sDefaultLanguage & " language in Sysprep", LogTypeInfo
		Set oCmdLinesFile = oFSO.CreateTextFile("C:\sysprep\i386\$OEM$\CmdLines.txt")
		If oFSO.FolderExists("C:\Local\Language") = False Then oFSO.CreateFolder "C:\Local\Language"
		oCmdLinesFile.WriteLine("[Commands]")
		oCmdLinesFile.WriteLine("C:\Local\Language\SetRegOpts.bat")
		oCmdLinesFile.Close
		Set oSetRegOptsFile = oFSO.CreateTextFile("C:\Local\Language\SetRegOpts.bat")
		oSetRegOptsFile.WriteLine("rundll32.exe shell32,Control_RunDLL intl.cpl,,/f:""C:\Local\Language\regopts.txt""")
		oFSO.CopyFile "M:\Language\" & sDefaultLanguage & "\Regopts.txt", "c:\Local\Language\Regopts.txt", True
		If oFSO.FolderExists("M:\Language\" & sDefaultLanguage & "\AdobeReader") Then
			LogInfo sLogFile, "Adding installation of Adobe Reader in " & sDefaultLanguage & " in Sysprep", LogTypeInfo
			If oFSO.FolderExists("C:\Local\Language\AdobeReader") = False Then oFSO.CreateFolder "C:\Local\Language\AdobeReader"
			oFSO.CopyFolder "M:\Language\" & sDefaultLanguage & "\AdobeReader", "C:\Local\Language\AdobeReader"
			Set oInstallFile = oFSO.OpenTextFile("C:\Local\Language\AdobeReader\Install.txt")
			Do While Not oInstallFile.AtEndOfStream
				oSetRegOptsFile.WriteLine(oInstallFile.ReadLine)
			Loop
			oInstallFile.Close
		End If
		If oFSO.FolderExists("M:\Language\" & sDefaultLanguage & "\MediaPlayer") Then
			LogInfo sLogFile, "Adding installation of Media Player in " & sDefaultLanguage & " in Sysprep", LogTypeInfo
			If oFSO.FolderExists("C:\Local\Language\MediaPlayer") = False Then oFSO.CreateFolder "C:\Local\Language\MediaPlayer"
			oFSO.CopyFolder "M:\Language\" & sDefaultLanguage & "\MediaPlayer", "C:\Local\Language\MediaPlayer"
			Set oInstallFile = oFSO.OpenTextFile("C:\Local\Language\MediaPlayer\Install.txt")
			Do While Not oInstallFile.AtEndOfStream
				oSetRegOptsFile.WriteLine(oInstallFile.ReadLine)
			Loop
			oInstallFile.Close
		End If
		If oFSO.FolderExists("M:\Language\" & sDefaultLanguage & "\Office") Then
			LogInfo sLogFile, "Adding installation of Office " & sDefaultLanguage & " Interface Pack in Sysprep", LogTypeInfo
			If oFSO.FolderExists("C:\Local\Language\Office") = False Then oFSO.CreateFolder "C:\Local\Language\Office"
			oFSO.CopyFolder "M:\Language\" & sDefaultLanguage & "\Office", "C:\Local\Language\Office"
			Set oInstallFile = oFSO.OpenTextFile("C:\Local\Language\Office\Install.txt")
			Do While Not oInstallFile.AtEndOfStream
				oSetRegOptsFile.WriteLine(oInstallFile.ReadLine)
			Loop
			oInstallFile.Close
		End If
		If oFSO.FolderExists("M:\Language\" & sDefaultLanguage & "\Windows") Then
			LogInfo sLogFile, "Adding installation of Windows " & sDefaultLanguage & " Interface Pack in Sysprep", LogTypeInfo
			If oFSO.FolderExists("C:\Local\Language\Windows") = False Then oFSO.CreateFolder "C:\Local\Language\Windows"
			oFSO.CopyFolder "M:\Language\" & sDefaultLanguage & "\Windows", "C:\Local\Language\Windows"
			Set oInstallFile = oFSO.OpenTextFile("C:\Local\Language\Windows\Install.txt")
			Do While Not oInstallFile.AtEndOfStream
				oSetRegOptsFile.WriteLine(oInstallFile.ReadLine)
			Loop
			oInstallFile.Close
		End If	
	End If
	
	LogInfo sLogFile, "------ Updating Install.ins file for Internet Explorer Configuration ------", LogTypeInfo
	If oFSO.FileExists("M:\INSTALL.INS") Then
		ErrorCode = SubCopyFile("M:\","C:\Program Files\Internet Explorer\Custom","INSTALL.INS")
	Else
		LogInfo sLogFile, "The file M:\INSTALL.INS doesn't exists", LogTypeError
	End If
	
	LogInfo sLogFile, "------ Preparing configuration of local groups ------", LogTypeInfo
	If oFSO.FileExists("C:\Local\Groups.ini") = False Then
		Dim oTemp
		Set oTemp = oFSO.CreateTextFile("C:\Local\Groups.ini", True)
		oTemp.close
		Set oTemp = Nothing
	End If
	If sAdminGroups <> "" Then UpdateIni "C:\Local\Groups.ini", "GROUPS", "AdminGroup", sAdminGroups
	If sRemoteAssistanceGroups <> "" Then UpdateIni "C:\Local\Groups.ini", "GROUPS", "HelpServicesGroup", sRemoteAssistanceGroups
	
	LogInfo sLogFile, "------ Preparing configuration of Admin password ------", LogTypeInfo
	If oFSO.FileExists("C:\Local\Password.ini") = False Then
		Set oTemp = oFSO.CreateTextFile("C:\Local\Password.ini", True)
		oTemp.close
		Set oTemp = Nothing
	End If
	If sLocalAdminPassword <> "" Then UpdateIni "C:\Local\Password.ini", "Password", "LocalAdminPassword", sLocalAdminPassword
	
	LogInfo sLogFile, "------ Configuration of the Outlook profile ------", LogTypeInfo
	If sExchangeServer <> "" Then
		UpdateIni "C:\Program Files\Microsoft Office\custom11.prf", "ServiceEGS", "HomeServer", sExchangeServer
		UpdateIni "C:\Program Files\Microsoft Office\custom11.prf", "Service1", "HomeServer", sExchangeServer
	End If
	If sWebmailServer <> "" Then UpdateIni "C:\Program Files\Microsoft Office\custom11.prf", "ServiceEGS", "RPCProxyServer", sWebmailServer
	
End Function

Function CopyLogFile(sLogFile, sLogFile2)
	On Error Resume Next

	Dim iRetVal, fptr1, fptr2, sLine

	iRetVal = Success
	CopyLogFile = iRetVal
	
	Set fptr1 = oFSO.OpenTextFile(sLogFile, ForReading, True)
	If Err then
		CopyLogFile = Failure
		LogInfo sLogfile, "ERROR - Opening " & sLogFile & " for reading. (errornum = " & Err.Number & ")(Error Description: " & Err.Description & ").", LogTypeError
		EXIT FUNCTION
	End if

	Set fptr2 = oFSO.OpenTextFile(sLogFile2, ForAppending, True)
	If Err then
		CopyLogFile = Failure
		LogInfo sLogfile, "ERROR - Opening " & sLogFile2 & " for appending. (errornum = " & Err.Number & ") (Error Description: " & Err.Description & ").", LogTypeError
		EXIT FUNCTION
	End if

	Do while Not fptr1.AtEndOfStream
	sLine = fptr1.readline
	fptr2.writeline sLine
	Loop

	fptr1.Close
	fptr2.Close
	oFSO.DeleteFile sLogFile,True
End Function

'//---------------------------------------------------------------------------
'//
'//  Function:	LogInfo()
'//
'//  Input:	sLogFile - name of logfile
'//		sLogMsg - message to append to Logfile
'//		iType - type of message to log (info, warning, error, flag)
'// 
'//  Return:	None
'//
'//  Purpose:	Write the message to the logfile and the script
'//		
'//---------------------------------------------------------------------------
Function LogInfo(sLogFile, sLogMsg, iType)

	Dim sTime, sDate

	sTime = Right("0" & Hour(Now), 2) & ":" & Right("0" & Minute(Now), 2) & ":" & Right("0" & Second(Now), 2) & ".000+000"
	sDate = Right("0"& Month(Now), 2) & "-" & Right("0" & Day(Now), 2) & "-" & Year(Now)

	LogfileAppend sLogfile, "<![LOG[" & sLogMsg & "]LOG]!><time=""" & sTime & """ date=""" & sDate & """ component=""" & sThisScriptName & """ context="""" type=""" & iType & """ thread="""" file=""" & sThisScriptName & """>"

	if bDebug then
		wscript.echo sLogMsg
	end if

End Function

'//---------------------------------------------------------------------------
'//
'//  Function:	LogFileAppend()
'//
'//  Input:	sLogFile - name of logfile
'//		sLogMsg - message to append to Logfile
'// 
'//  Return:	Success - 0
'//		Failure - 1
'//
'//  Purpose:	Add a string to the Log File
'//		
'//---------------------------------------------------------------------------
Function LogfileAppend(sLogFile, sLogMsg)

	Dim iRetVal, fptr

	iRetVal = Success

	On Error Resume Next

	Set fptr = oFSO.OpenTextFile(sLogFile, ForAppending, True)
	if Err then
		LogFileAppend = Failure
		Err.Clear
		EXIT FUNCTION
	end if

	fptr.writeline(sLogMsg)
	fptr.close

	LogfileAppend = iRetVal
End Function

'//---------------------------------------------------------------------------
'//
'//  Function:	GetAssetInfoByWMI()
'//
'//  Input:	sAssetTag - machine's SMBIOS asset tag
'//		sSerialNumber  - machine's serial number
'//		sMake - machine's make (manufacturer)
'//		sModel - machine's model
'//		sProduct - machine's product
'//		sUUID - machine's UUID
'//		bIsLaptop - indicates the machine is a laptop
'//		bIsDesktop - indicates the machine is a desktop
'//		bIsServer - indicates the machine is a server
'// 
'//  Return:	Success - 0
'//		Failure - 1
'//
'//  Purpose:	Get asset information using WMI
'//		
'//---------------------------------------------------------------------------
Function GetAssetInfoByWMI(sSerialNumber, sMake, sModel, bIsLaptop, bIsDesktop, bIsServer)

	Dim objResults, objInstance
        Dim i
	
	' Get the SMBIOS asset tag from the Win32_SystemEnclosure class
	Set objResults = oWMI.InstancesOf("Win32_SystemEnclosure")
	bIsLaptop = false
	bIsDesktop = false
	bIsServer = false
	For each objInstance in objResults

		If objInstance.ChassisTypes(0) = 12 or objInstance.ChassisTypes(0) = 21 then
			' Ignore docking stations
		Else
			Select Case objInstance.ChassisTypes(0)
			Case "8", "10", "12", "14", "18", "21"
				bIsLaptop = true
			Case "3", "4", "5", "6", "7", "15"
				bIsDesktop = true
			Case "23"
				bIsServer = true
			Case Else
				' Do nothing
			End Select
		End if
	Next
	LogInfo sLogFile, "IsLaptop = " & bIsLaptop, LogTypeInfo
	LogInfo sLogFile, "IsDesktop = " & bIsDesktop, LogTypeInfo
	LogInfo sLogFile, "IsServer = " & bIsServer, LogTypeInfo


	' Get the serial number from the Win32_BIOS class.  Also figure out if ACPI is sufficient.

	Set objResults = oWMI.InstancesOf("Win32_BIOS")
	For each objInstance in objResults

                ' Get the serial number

		If not IsNull(objInstance.SerialNumber) then
			sSerialNumber = Trim(objInstance.SerialNumber)
		End if

	Next
	If sSerialNumber = "" then
		LogInfo sLogFile, "WARNING - Unable to determine serial number via WMI.", LogTypeWarning
	Else
		LogInfo sLogFile, "Serial number = " & sSerialNumber, LogTypeInfo
	End if


	' Get the make and model from the Win32_ComputerSystem class

	Set objResults = oWMI.InstancesOf("Win32_ComputerSystemProduct")
	For each objInstance in objResults

		If not IsNull(objInstance.Vendor) then
			sMake = Trim(objInstance.Vendor)
		End if
		If not IsNull(objInstance.Name) then
			sModel = Trim(objInstance.Name)
		End if
	Next
	If sMake = "" then
		LogInfo sLogFile, "WARNING - Unable to determine make via WMI.", LogTypeWarning
	Else
		LogInfo sLogFile, "Make = " & sMake, LogTypeInfo
	End if
	If sModel = "" then
		LogInfo sLogFile, "WARNING - Unable to determine model via WMI.", LogTypeWarning
	Else
		LogInfo sLogFile, "Model = " & sModel, LogTypeInfo
	End if
End Function

'//---------------------------------------------------------------------------
'//
'//  Function:	GetNetworkInfoByWMI()
'//
'//  Input:	dicIPAddresses - IP addresses of local machine
'//		dicMacAddresses  - MAC addresses of local machine
'//		dicDefaultGateways - default gateways of local machine
'// 
'//  Return:	Success - 0
'//		Failure - 1
'//
'//  Purpose:	Get network details using WMI
'//		
'//---------------------------------------------------------------------------
Function GetNetworkInfoByWMI(sIPAddress, sMacAddress, sDefaultGateway)

	Dim iRetVal, objNetworkAdapters, objAdapter, sElement, sTmp1, arrTmp

	iRetVal = Success


	' Get a list of IP-enabled adapters

	Set objNetworkAdapters = oWMI.ExecQuery("select * from Win32_NetworkAdapterConfiguration where IPEnabled = 1")

	For Each objAdapter In objNetworkAdapters

		LogInfo sLogFile, "Checking network adapter: " & objAdapter.Caption, LogTypeInfo

		' Get the MAC address

		sMacAddress = objAdapter.MacAddress
		LogInfo sLogFile, "MAC address = " & objAdapter.MacAddress, LogTypeInfo

		' Get the IP addresses

		If not (IsNull(objAdapter.IPAddress)) then
			for each sElement in objAdapter.IPAddress
				if sElement = "0.0.0.0" or Left(sElement, 7) = "169.254" or sElement = "" then
					LogInfo sLogFile, "Ignoring IP Address " & sElement, LogTypeInfo
				else
					sIPAddress = sElement
					LogInfo sLogFile, "IP Address = " & sElement, LogTypeInfo
				end if
			next
		End if

		' Get the default gateway values

		If not (IsNull(objAdapter.DefaultIPGateway)) then
			for each sElement in objAdapter.DefaultIPGateway
				if sElement <> "" then
					sDefaultGateway = sElement
					LogInfo sLogFile, "Default Gateway = " & sElement, LogTypeInfo
				end if
			next
		End if

	next  

	GetNetworkInfoByWMI = iRetVal
	LogInfo sLogFile, "Finished retrieving network info via WMI", LogTypeInfo

End Function

'//---------------------------------------------------------------------------
'//
'//  Function:	UpdateSysprepInf()
'//
'//  Input:	sIniFile - Path and name of ini file to read
'//		sSectionSysprepMapping - section in Ini file that has the sysprep mappings
'//		arrSysprepKeys - array of Sysprep keys contained in the ini file
'//		arrSysprepValues - array of sysprep values contained in the ini file
'//		sSysprepInf - Full path of sysprep.inf file
'// 
'//  Return:	Success - 0
'//		Failure - 1
'//
'//  Purpose:	Update the Sysprep.inf file with information retrieved by this script.
'//		
'//---------------------------------------------------------------------------
Function UpdateSysprepInf(sSysprepInf)

	Dim iRetVal, sElement, sPrev, sSysprepSection
	Dim sCurrentPath, arrCurrentPaths, sTmp, dicDriverPaths, sNewPath
	Dim re, tmpArray

	iRetVal = Success

	Set re = new regexp
	re.IgnoreCase = True
	re.Global = True

	SplashMsg2 "Sysprep Update"
	LogInfo sLogFile, "------ Updating Sysprep.inf ------", LogTypeInfo
	' Update the specified values

	UpdateSysprepSection sSysprepInf, "Unattended", "INSTALLFILESPATH", "C:\Sysprep\i386"
	UpdateSysprepSection sSysprepInf, "UserData", "COMPUTERNAME", sComputerName
	UpdateSysprepSection sSysprepInf, "UserData", "FULLNAME", sFullName
	UpdateSysprepSection sSysprepInf, "UserData", "ORGNAME", sOrgName
	If sMasterImageType = "XP" Then UpdateSysprepSection sSysprepInf, "UserData", "PRODUCTKEY", sVolumeLicenseKey
	If sMasterImageType = "XPTabletPC" Then UpdateSysprepSection sSysprepInf, "UserData", "PRODUCTKEY", sVolumeLicenseKeyTabletPC
	UpdateSysprepSection sSysprepInf, "GuiUnattended", "TIMEZONE", sTimeZone
	UpdateSysprepSection sSysprepInf, "Identification", "JOINDOMAIN", sDomain
	UpdateSysprepSection sSysprepInf, "Identification", "DOMAINADMIN", sDomainAccount
	UpdateSysprepSection sSysprepInf, "Identification", "DOMAINADMINPASSWORD", sDomainPassword
	
	' Get the current list of driver paths from Sysprep.inf

	Set dicDriverPaths = CreateObject("Scripting.Dictionary")
	dicDriverPaths.CompareMode = TextCompare
	iRetVal = GetIniValue(sSysprepInf, "Unattended", "OemPnPDriversPath", sCurrentPath)
	sCurrentPath = Trim(sCurrentPath)
	re.Pattern = Chr(9)  ' Tab
	sCurrentPath = re.Replace(sCurrentPath, "")
	LogInfo sLogFile, "Original " & sSysprepInf & " section [Unattended] OemPnPDriversPath=" & sCurrentPath, LogTypeInfo
	If Len(sCurrentPath) = 0 then
		LogInfo sLogFile, "WARNING - Current Sysprep.inf did not contain OemPnPDriversPath entry.", LogTypeWarning
	ElseIf Left(sCurrentPath,1) = """" then
		sCurrentPath = Mid(sCurrentPath,2,Len(sCurrentPath)-2)  ' Remove quotes, we'll put them back later
	End if
	arrCurrentPaths = Split(sCurrentPath, ";")
	For each sTmp in arrCurrentPaths
		If not dicDriverPaths.Exists(sTmp) then
			dicDriverPaths.Add sTmp, ""
		End if
	Next


	' Add the list of paths found in the Drivers directory (use the same drive letter as Sysprep.inf)

	If oFSO.FolderExists("C:\Drivers") then
		LogInfo sLogFile, "Checking ""C:\Drivers"" for driver directories to add", LogTypeInfo
		GetDriverPaths dicDriverPaths, "C:\Drivers", True
	Else
		LogInfo sLogFile, "Driver directory ""C:\Drivers"" does not exist, creating it.", LogTypeWarning
		On Error Resume Next
		oFSO.CreateFolder "C:\Drivers"
		On Error Goto 0
	End if

	' Build the new path and write it back to the Sysprep.inf

	sNewPath = ""
	For each sTmp in dicDriverPaths.Keys
		sNewPath = sNewPath & ";" & sTmp
	Next
	sNewPath = """" & Mid(sNewPath,2) & """"
	WriteIni sSysprepInf, "Unattended", "OemPnPDriversPath", sNewPath
	LogInfo sLogFile, "Updated " & sSysprepInf & " section [Unattended] with OemPnPDriversPath=" & sNewPath, LogTypeInfo


	UpdateSysprepInf = iRetVal

End Function

Sub UpdateSysprepSection(sSysprepInf, sSysprepSection, sElement, sValue)
	If Len(sSysprepSection) > 0 Then
		If len(sValue) > 0 Then
			WriteIni sSysprepInf, sSysprepSection, sElement, sValue				 ' No quotes needed
			If UCase(sElement) = "JOINDOMAIN" Then
				WriteIni sSysprepInf, sSysprepSection, "JoinWorkgroup", ""						 ' Don't allow a conflict
			End if
			LogInfo sLogFile, "Updated " & sSysprepInf & " section [" & sSysprepSection & "] with " & sElement & "=" & sValue, LogTypeInfo
		Else
			LogInfo sLogFile, "Warning - Unable to update Sysprep.inf with element " & sElement & ", value is blank.", LogTypeWarning
		End if
	Else
		' LogInfo sLogFile, "No mapping for element " & sElement & " was found in section [" & sSectionSysprepMapping & "], ignoring this element.", LogTypeWarning
	End If
End Sub

Sub Updateini(sInifile, sSection, sElement, sValue)
	If Len(sSection) > 0 Then
		If len(sValue) > 0 Then
			WriteIni sInifile, sSection, sElement, sValue
			LogInfo sLogFile, "Updated " & sInifile & " section [" & sSection & "] with " & sElement & "=" & sValue, LogTypeInfo
		Else
			LogInfo sLogFile, "Warning - Unable to update Sysprep.inf with element " & sElement & ", value is blank.", LogTypeWarning
		End if
	Else
		' LogInfo sLogFile, "No mapping for element " & sElement & " was found in section [" & sSectionSysprepMapping & "], ignoring this element.", LogTypeWarning
	End If
End Sub

'//---------------------------------------------------------------------------
'//
'//  Function:	UpdateDevicePath()
'//
'//  Input:	none
'// 
'//  Return:	Success - 0
'//		Failure - 1
'//
'//  Purpose:	Update the DevicePath registry key with the Driver directories.
'//		
'//---------------------------------------------------------------------------
Function UpdateDevicePath()

	Dim iRetVal, sElement, sPrev, sSysprepSection
	Dim sCurrentPath, arrCurrentPaths, sTmp, dicDevicePaths, sNewPath
	Dim sDir

	iRetVal = Success

	SplashMsg2 "DevicePath Update"
	LogInfo sLogFile, "------ Updating DevicePath Registry Value ------", LogTypeInfo


	' Find the "software" hive

	iRetVal = oWshShell.Run("reg load HKLM\NewOS ""C:\Windows\system32\config\software""", 0, true)
	If iRetVal = Success then
		LogInfo sLogFile, "Successfully loaded new OS software registry hive using ""C:\Windows\system32\config\software""." , LogTypeInfo
	End if
	
	If iRetVal <> Success then
		LogInfo sLogFile, "Unable to load new OS registry file; DevicePath cannot be updated.", LogTypeWarning
		UpdateDevicePath = Failure
		EXIT FUNCTION
	End if


	' Get the current DevicePath registry key

	Set dicDevicePaths = CreateObject("Scripting.Dictionary")
	dicDevicePaths.CompareMode = TextCompare
	sCurrentPath = oWshShell.RegRead("HKEY_LOCAL_MACHINE\NewOS\Microsoft\Windows\CurrentVersion\DevicePath")
	sCurrentPath = Trim(sCurrentPath)
	LogInfo sLogFile, "Original DevicePath=" & sCurrentPath, LogTypeInfo

	arrCurrentPaths = Split(sCurrentPath, ";")
	For each sTmp in arrCurrentPaths
		If not dicDevicePaths.Exists(sTmp) then
			dicDevicePaths.Add sTmp, ""
		End if
	Next


	' Add the list of paths found in the Drivers directory (use the same drive letter as Sysprep.inf)

	If oFSO.FolderExists("C:\Drivers") then
		LogInfo sLogFile, "Checking ""C:\Drivers"" for driver directories to add", LogTypeInfo
		GetDriverPaths dicDevicePaths, "C:\Drivers", False
	Else
		LogInfo sLogFile, "Driver directory ""C:\Drivers"" not found, impossible to add driver paths.", LogTypeWarning
		UpdateDevicePath = Failure
		EXIT FUNCTION
	End if


	' Build the new path and write it back to the Sysprep.inf

	sNewPath = ""
	For each sTmp in dicDevicePaths.Keys
		sNewPath = sNewPath & ";" & sTmp
	Next
	sNewPath = Mid(sNewPath,2)  ' Strip leading semicolon
	oWshShell.RegWrite "HKEY_LOCAL_MACHINE\NewOS\Microsoft\Windows\CurrentVersion\DevicePath", sNewPath, "REG_EXPAND_SZ"
	LogInfo sLogFile, "Updated DevicePath=" & sNewPath, LogTypeInfo


	' Unload the registry file

	oWshShell.Run "reg unload HKLM\NewOS", 0, true

	UpdateDevicePath = iRetVal

End Function

'//---------------------------------------------------------------------------
'//
'//  Function:	CopyDrivers(sPath)
'//
'//  Input:	None
'//
'//  Return:	Success - 0
'//		Failure - 1
'//
'//  Purpose:	Copy any specified driver paths to the Drivers directory
'//
'//---------------------------------------------------------------------------
Function CopyDrivers(sPath)
	Dim iRetVal, iCopied

	CopyDrivers = Success
	iCopied = 0

	If oFSO.FolderExists(sPath) = False Then 
		LogInfo sLogFile, "No DriverPath key was specified - no copying will be done.", LogTypeInfo
		EXIT FUNCTION
	End if

	LogInfo sLogFile, "Checking to see if drivers need to be copied.", LogTypeInfo

	If not oFSO.FolderExists("C:\Drivers") then
		oFSO.CreateFolder "C:\Drivers"
	End If
	
	SplashMsg2 "Copying Drivers"
	iRetVal = CopyDriverDir(sPath)
	If iRetVal = Success then
		iCopied = 1
	End if
	LogInfo sLogFile, CStr(iCopied) & " driver directories copied successfully.", LogTypeInfo

End Function


'//---------------------------------------------------------------------------
'//
'//  Function:	CopyDriverDir()
'//
'//  Input:	sPath - Path of directory to copy to C:\Drivers
'//
'//  Return:	Success - 0
'//			 Failure - 1
'//
'//  Purpose:	Copies a specific driver directory to C:\Drivers
'//
'//---------------------------------------------------------------------------
Function CopyDriverDir(sPath)

	Dim iRetVal


	' Make sure the network path specified exists

	If not oFSO.FolderExists(sPath) then
		LogInfo sLogFile, "WARNING - Invalid driver path " & sPath & " specified - no copying will be done.", LogTypeWarning
		CopyDriverDir = Failure
		EXIT FUNCTION
	End if
	
	' Copy the drivers

	LogInfo sLogFile, "Copying drivers from """ & sPath & """ to ""C:\Drivers""", LogTypeInfo

	On Error Resume Next	
	iRetVal = oWshShell.Run("xcopy """ & sPath & """ ""C:\Drivers"" /s /e /h /y /c", 0, true)
	If Err then
		LogInfo sLogFile, "ERROR copying """ & sPath & """ to ""C:\Drivers"": " & Err.Description & " (" & Err.Number & ")", LogTypeError
		CopyDriverDir = Failure
		EXIT FUNCTION
	ElseIf iRetVal <> Success then
		LogInfo sLogFile, "ERROR copying """ & sPath & """ to ""C:\Drivers"", XCOPY rc = " & iRetVal, LogTypeError
		CopyDriverDir = Failure
		EXIT FUNCTION
	End if
	On Error Goto 0

End Function

Sub HTAEXEC(CMDLINE)
	oWshShell.run "mshta.exe  """ & CurrentScriptFolder & "ask-UI.hta"" """ & CMDLINE & "",0,True
End Sub

'//---------------------------------------------------------------------------
'//
'//  Function:	GetDriverPaths()
'//
'//  Input:	dicPaths - dictionary object to hold retrieved paths
'//		sPath - path to check
'//		bRelative - flag to indicate whether paths should be relative
'//
'//  Return:	(via dicPaths)
'//
'//  Purpose:	Scan the specified directory to determine what paths need to be
'//		added 
'//
'//---------------------------------------------------------------------------
Sub GetDriverPaths(dicPaths, sPath, bRelative)

	Dim objFolder, objFile, objSubFolder
	dim sCurrentDir

	' See if there are any INF files in the current directory

	Set objFolder = oFSO.GetFolder(sPath)
	For each objFile in objFolder.Files
		If UCase(oFSO.GetExtensionName(objFile.Name)) = "INF" then
			If bRelative then
				sCurrentDir = Mid(objFolder.Path, 3)
			Else
				sCurrentDir = "%SystemDrive%" & Mid(objFolder.Path, 3)
			End if
			If not dicPaths.Exists(sCurrentDir) then
				dicPaths.Add sCurrentDir, ""
				LogInfo sLogFile, "Found new driver path: " & sCurrentDir, LogTypeInfo
			End if
			Exit For
		End if
	Next


	' Check each of the subfolders
	For each objSubFolder in objFolder.SubFolders
		GetDriverPaths dicPaths, objSubFolder.Path, bRelative
	Next

End Sub

'//---------------------------------------------------------------------------
'//
'//  Function:	GetIniValue()
'//
'//  Input:	sIniFile - Path and name of ini file to read
'//		sSection - Section to get value
'//		sKey - Key associated with value
'//		sValue - to be filled in with the value
'// 
'//  Return:	Success - 0
'//		Failure - 1
'//
'//  Purpose:	Get value from ini file
'//		
'//---------------------------------------------------------------------------
Function GetIniValue(sIniFile, sSection, sKey, sValue)

	Dim iRetVal

	iRetVal = Success


	sValue = ReadIni(sIniFile, sSection, sKey)

	if len(sValue) = 0 then
	iRetVal = Failure
	end if	

	GetIniValue = iRetVal

End Function

'//---------------------------------------------------------------------------
'//
'//  Function:	ReadIni()
'//
'//  Input:	file - name of INI file
'//		section - section within the INI file
'//		item - name of the item in the section to retrieve
'//
'//  Return:	value of the specified item
'//
'//  Purpose:	Read settings from the specified INI file
'//
'//---------------------------------------------------------------------------
Function ReadIni(file, section, item)

	Dim line, equalpos, leftstring, ini

	ReadIni = ""
	file = Trim(file)
	item = Trim(item)
	Set ini = oFSO.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 Function

'//---------------------------------------------------------------------------
'//
'//  Function:	WriteIni()
'//
'//  Input:	file - name of INI file
'//		section - section within the INI file
'//		item - name of the item in the section to retrieve
'//		myvalue - new value to be written
'//
'//  Return:	None
'//
'//  Purpose:	Write settings to the specified INI file
'//
'//---------------------------------------------------------------------------
Sub WriteIni( file, section, item, myvalue )

	Dim in_section, section_exists, item_exists, wrote, itemtrimmed
	Dim read_ini, write_ini, temp_ini, linetrimmed, line, equalpos
	Dim leftstring

	in_section = False
	section_exists = False
	item_exists = ( ReadIni( file, section, item ) <> "" )
	wrote = False
	file = Trim(file)
	itemtrimmed = Trim(item)
	myvalue = Trim(myvalue)

	temp_ini = oFSO.GetParentFolderName(file) & "\" & oFSO.GetTempName

	Set read_ini = oFSO.OpenTextFile( file, 1, True, False )
	Set write_ini = oFSO.CreateTextFile( temp_ini, False)

	While read_ini.AtEndOfStream = False
		line = read_ini.ReadLine
		linetrimmed = Trim(line)
		If wrote = False Then
			If LCase(line) = "[" & LCase(section) & "]" Then
				section_exists = True
				in_section = True
			ElseIf InStr( line, "[" ) = 1 Then
				in_section = False
			End If
		End If

		If in_section Then
			If itemtrimmed = "" then
				' Do nothing: we want to wipe the section
			ElseIf item_exists = False Then
				write_ini.WriteLine line
				If myvalue <> "" then
					write_ini.WriteLine item & "=" & myvalue
				End if
				wrote = True
				in_section = False
			Else
				equalpos = InStr(1, line, "=", 1 )
				If equalpos > 0 Then
					leftstring = Left(line, equalpos - 1 )
					leftstring = Trim(leftstring)
					If LCase(leftstring) = LCase(item) Then
						If myvalue <> "" then
							write_ini.WriteLine itemtrimmed & "=" & myvalue
						End if
						wrote = True
						in_section = False
					End If
				End If
				If Not wrote Then
					write_ini.WriteLine line
				End If
			End If
		Else
			write_ini.WriteLine line
		End If
	Wend

	If section_exists = False and itemtrimmed <> "" Then ' section doesn't exist
		write_ini.WriteLine
		write_ini.WriteLine "[" & section & "]"
		If myvalue <> "" then
			write_ini.WriteLine itemtrimmed & "=" & myvalue
		End if
	End If

	read_ini.Close
	write_ini.Close
	If oFSO.FileExists(file) then
		oFSO.DeleteFile file, True
	End if
	oFSO.CopyFile temp_ini, file, true
	oFSO.DeleteFile temp_ini, True

End Sub

Function UpdateSequencer(Master,Profile)
	Dim oFile
	SplashMsg2 "Sequencer Update"
	LogInfo sLogFile, "------ Updating Sequencer File for Master " & Master & " ------", LogTypeInfo
	If oFSO.FileExists("M:\Images\" & Master & ".txt") Then
		UpdateSequencer = UpdateSequencerFile("M:\Images\" & Master & ".txt")
	Else
		LogInfo sLogFile, "The file M:\Images\" & Master & ".txt doesn't exists", LogTypeError
		UpdateSequencer = Failure
		Exit Function
	End If
	
	LogInfo sLogFile, "------ Updating Sequencer File for Profile " & Profile & " ------", LogTypeInfo
	If oFSO.FileExists("M:\ProfileType\" & Profile & ".txt") Then
		UpdateSequencer = UpdateSequencerFile("M:\ProfileType\" & Profile & ".txt")
	Else
		LogInfo sLogFile, "The file M:\ProfileType\" & Profile & ".txt doesn't exists", LogTypeError
		UpdateSequencer = Failure
		Exit Function
	End If
	
	LogInfo sLogFile, "------ Updating Sequencer File with Final Actions ------", LogTypeInfo
	If oFSO.FileExists("M:\Images\FinalActions.txt") Then
		UpdateSequencer = UpdateSequencerFile("M:\Images\FinalActions.txt")
	Else
		LogInfo sLogFile, "The file M:\Images\FinalAction.txt doesn't exists", LogTypeError
		UpdateSequencer = Failure
		Exit Function
	End If
	
	LogInfo sLogFile, "------ Updating NetworkConnect.cmd ------", LogTypeInfo
	If cArgs.length = 2 Then
		Set oFile = oFSO.OpenTextFile("C:\NetworkConnect.cmd",FORWRITING,True)
		UpdateSequencer = oFile.WriteLine("@echo off")
		UpdateSequencer = oFile.WriteLine("net use M: /delete")
		UpdateSequencer = oFile.WriteLine("net use M: \\" & cArgs(0) & "\Deploy$ " & cArgs(1) & " /user:" & cArgs(0) & "\DesktopDeployUser")
		oFile.Close
		
		Set oFile = oFSO.OpenTextFile("C:\Local\Master\NetworkConnect.cmd",FORWRITING,True)
		UpdateSequencer = oFile.WriteLine("@echo off")
		UpdateSequencer = oFile.WriteLine("net use M: /delete")
		UpdateSequencer = oFile.WriteLine("net use M: \\" & cArgs(0) & "\Deploy$ " & cArgs(1) & " /user:" & cArgs(0) & "\DesktopDeployUser")
		oFile.Close
	ElseIf oFSO.FileExists("M:\Images\NetworkConnect.cmd") Then
		UpdateSequencer = SubCopyFile("M:\Images","C:\","NetworkConnect.cmd")
		UpdateSequencer = SubCopyFile("M:\Images","C:\Local\Master","NetworkConnect.cmd")
	Else
		LogInfo sLogFile, "The file M:\Images\NetworkConnect.cmd doesn't exists", LogTypeError
		UpdateSequencer = Failure
		Exit Function
	End If
End Function

Function UpdateSequencerFile(FileName)
	Dim oFile,oFile2,sLine
	
	Set oFile = oFSO.OpenTextFile(FileName, ForReading, True)
	If Err Then
		UpdateSequencerFile = Failure
		LogInfo sLogfile, "ERROR - Opening " & FileName & " for reading. (errornum = " & Err.Number & ")(Error Description: " & Err.Description & ").", LogTypeError
		Exit Function
	End if

	Set oFile2 = oFSO.OpenTextFile("C:\Local\Master\_master.txt", ForAppending, True)
	If Err Then
		UpdateSequencerFile = Failure
		LogInfo sLogfile, "ERROR - Opening C:\Local\Master\_master.txt for appending. (errornum = " & Err.Number & ") (Error Description: " & Err.Description & ").", LogTypeError
		Exit Function
	End if

	Do While Not oFile.AtEndOfStream
		sLine = oFile.readline
		oFile2.writeline sLine
		LogInfo sLogFile, "Updated C:\Local\Master\_master.txt with " & sLine, LogTypeInfo
	Loop

	oFile.Close
	oFile2.Close
	UpdateSequencerFile = Success
End Function

'------------------------------------------------------------------------------
' Function SubCopyFile
'------------------------------------------------------------------------------
Function SubCopyFile(Path1,Path2,Filename)
	On Error Resume Next
	Dim oFSO
	Set oFSO = CreateObject("Scripting.FileSystemObject")
	err.Clear
	If Filename <> "" Then
		RemoveReadOnlyFile(oFSO.BuildPath(Path2,Filename))
		err.Clear
		oFSO.CopyFile oFSO.BuildPath(Path1,Filename), oFSO.BuildPath(Path2,Filename), True
		If err.number=0 Then
			RemoveReadOnlyFile(oFSO.BuildPath(Path2,Filename))
			LogInfo sLogFile, oFSO.BuildPath(Path2,Filename) & " - Copy is OK", LogTypeInfo
		Else
			LogInfo sLogfile, "ERROR - Copying " & oFSO.BuildPath(Path2,Filename) & ". (errornum = " & Err.Number & ") (Error Description: " & Err.Description & ").", LogTypeError
		End If
	End If
	SubCopyFile = err.number
End Function

'------------------------------------------------------------------------------
' Function RemoveReadOnlyFile
'------------------------------------------------------------------------------
Function RemoveReadOnlyFile(oFileSpec)
	Dim oFSO,oFile
	Set oFSO = CreateObject("Scripting.FileSystemObject")
	If oFSO.FileExists(oFileSpec) Then
		Set oFile = oFSO.GetFile(oFileSpec)
		If oFile.attributes And 1 Then oFile.attributes = oFile.attributes - 1
	End If
End Function

'------------------------------------------------------------------------------
' Function SplashMsg
'------------------------------------------------------------------------------
Sub SplashMsg(sDisplay)
	oWshShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\SplashMsg\CurrentDisplayInfo" ,sDisplay
End Sub

'------------------------------------------------------------------------------
' Function SplashMsg
'------------------------------------------------------------------------------
Sub SplashMsg2(sDisplay)
	oWshShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\SplashMsg\CurrentDisplayInfo2" ,sDisplay
	WScript.Sleep 1000
End Sub
