'==========================================================================
'
' NAME: Script-PA-GP-VPN-In-M-R1.vbs
'
' AUTHOR:  Max Erenburg 
' DATE  : 4/23/2018
'
' COMMENT: This script is executed by the Global Protect client post VPN connection
' Will execute the base wrapper script as if the asset was first started up on the
' network and ends with performing a gpupdate to apply any new policies.
' Update 4/25/2018 script will be executed off local file system and check connectivity before proceeding
' Update 06/07/2018 network execution location change (Clients\GlobalProtect\).
' Update 09/13/2018 Turned off success (debug logging)
'==========================================================================

Option Explicit

Dim vDate, vTime, altTime, altDate, vDateTime
vDateTime = Now

Dim oShell, oFSO, oProcessEnv, sScript, iErrCode, sMsg
Dim sDebug, sDebugBlat, sSuccess, sPilot
Dim sMailbox1, sMailbox2, sRelayHost, sCN, sFQDN, sTry
Dim sSystem32, sLogDir, sScriptsDir, sEmailDir, sDebugLog
Dim sDomFQDN, sLib, sBlat, sEngKey
Dim sCoreBlat, sCoreBlat2, sCoreWMI, sCoreInfo, sCoreInfo2, sCoreInfo3, DebugLog
Dim oWMI, sWMIFailed, sWMIMsgBody2
Dim ProductName, IsServer, CSDver, s64Bit, DC
Dim description, address, subnet, subnetmask

Set oShell = CreateObject("WScript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oProcessEnv = oShell.Environment("PROCESS")

Const DEPLOYNAME = "PA-GP-VPN-In"
Const SIDE = "-M"
Const RELEASE = "-R1"
sScript = "Script-" & DEPLOYNAME & SIDE & RELEASE

sDebug = "False" : sDebugBlat = "False"
sSuccess = "False" ' Set to False if you dont want success emails. ' For enterprise deployment set to false, for one off installations leave as True
sPilot = "False" ' Set to False if you dont want attachment of debug file to success emails. ' Use for QA/UAT, once ready for Production deployments set to False

sMailbox1 = "merenburg@theorchard.com" : sMailbox2 = ""
sRelayHost = "smtp-relay.gmail.com"
sCN = oProcessEnv("COMPUTERNAME")
sFQDN = "@TheOrchard.com"
sTry = "2"

sSystem32 = oProcessEnv("SYSTEMROOT") & "\system32\"
sLogDir = oProcessEnv("SYSTEMROOT") & "\EngLogs"
sScriptsDir = sLogDir & "\Scripts"
sEmailDir = sLogDir & "\Email"
sDebugLog = sScriptsDir & "\" & sScript & ".log"

sBlat = sSystem32 & "blat.exe"
sEngKey = "HKLM\SOFTWARE\ORCDENG\"

' Initialize WMI connection to cimv2
On Error Resume Next 
Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
If Err.Number <> 0 Then
	iErrCode = Err.Number
	sWMIFailed = "Failed"
	sWMIMsgBody2 = Now & "__ Script was unable to successfully connect to cimv2, Error code: " & iErrCode & ", installations are dependent on WMI being healthy, cannot proceed."
End If
On Error GoTo 0

sMsg = "Scriptname: " & WScript.ScriptName
sMsg = sMsg & "|ScriptPath: " & WScript.ScriptFullName

' Ensure email alerts are available
Call CopyBlat

' Create directory(s) for local centralized logging
Call CreateLogDirs

' Create debug log or append to log if this script has been run before
Call CreateDebugLog("FirstCheck")

' Get what OS, CSD version are we working with
Call GetOSInfo

If sWMIFailed = "Failed" Then 'fail with hard error as we need WMI up and running (health to perform installs, etc..)
	If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
	WSHLog "CriticalFailure", sWMIMsgBody2
End If

' Get Nic information we are working with
Call GetNetworkInterface

' Check if DC Function
Call IsDC

Dim sConnectivity
Call CheckConnectivity
If sConnectivity = "Established" Then
	' Get Domain Name we are working with so we dont have to have additional copies of same script per AD Forest/Domain.
	Call GetDomainName
	sLib = "\\" & sDomFQDN & "\netlogon\lib\"

	' Based on asset classification, run next scripts
	Call ExecNextScripts
End If

If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Wrapper execution complete, total execution time: " & DateDiffToWords(vDateTime,Now))
WSHLog "Information", "Wrapper execution complete, total execution time: " & DateDiffToWords(vDateTime,Now)

' Log/email exit code, cleanup and exit
If Not (IsNull(iErrCode) Or IsEmpty(iErrCode)) Then
	If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
	DebugLog.WriteLine(Now & "__ Exiting... Wrapper exit code : " & iErrCode)
	If (sSuccess = "True") And (sPilot = "False") And (sCoreBlat = "") Then Email sScript & " Status", "Wrapper exit code : " & iErrCode & "|" & sMsg
	Call Cleanup(sScript & " Status", "Wrapper exit code : " & iErrCode & "|" & sMsg)
	WScript.Quit(iErrCode)
Else
	If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Exiting... Wrapper exit code  : " & Err.Number)
	If (sSuccess = "True") And (sPilot = "False") And (sCoreBlat = "") Then Email sScript & " Status", "Wrapper exit code  : " & Err.Number & "|" & sMsg
	Call Cleanup(sScript & " Status", "Wrapper exit code  : " & Err.Number & "|" & sMsg)
	WScript.Quit
End If

' ------   Packager's defined Functions/Subs section    -------

' Based on asset classification, run next scripts
Function ExecNextScripts
	If IsServer = "True" Then
		If DC = "True" Then
			iErrCode = "999"
			sMsg = "Something wrong, script was executed on a DC.| |" & sMsg
		Else ' All servers are x64
			iErrCode = "999"
			sMsg = "Something wrong, script was executed on a Server, should not be using Global Protect.| |" & sMsg
		End If
	Else ' Clients
		Call ExecScript("Clients", "Script-Compliance-1.0.0-M-R1.vbs")
		Call CheckConnectivity ' before every script execution.
		If sConnectivity = "Established" Then
			Call GPUpdate
		End If
	End If
End Function

Sub ExecScript(sClass, sNSN)
	On Error Resume Next
	Dim sCMD, vCT, iStat, iErrDesc
	If UCase(sClass) = "CLIENTS" Then
		sCMD = "\\" & sDomFQDN & "\netlogon\Clients\" & sNSN
	Else ' Client
		If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
		DebugLog.WriteLine(Now & "__ Unknown Class specified: " & sClass & ".")
		WSHLog "CriticalFailure", "Unknown Class specified: " & sClass & "."
	End If
	If Not oFSO.FileExists(sCMD) Then
		If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
		DebugLog.WriteLine(Now & "__ Script " & sCMD & " doesnt exist to execute.")
		WSHLog "Warning", "Script " & sCMD & " doesnt exist to execute."
	Else
		If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Executing" & sCMD)
		vCT = Now
		iStat = CreateObject("WScript.Shell").Run("wscript.exe " & Chr(34) & sCMD  & Chr(34), 1, True)
		If iStat = 0 Then
			If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Execution completed, exit code: " & iStat & ", total execution time: " & DateDiffToWords(vCT,Now))
		Else
			iErrCode = iStat
			iErrDesc = CStr(iStat) & " " & Err.Description & "."
			If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
			DebugLog.WriteLine(Now & "__ Execution of " & sCMD & ", FAILED. Result code: " & iErrDesc)
			WSHLog "Warning", "Execution of " & sCMD & ", FAILED. Result code: " & iErrDesc
		End If
	End If
	iStat = Null
	On Error GoTo 0
End Sub

' Execution GPupdate Function
Function GPUpdate
	On Error Resume Next
	Dim sCMD, vCT, iStat, iErrDesc
	sCMD = "gpupdate.exe /force"
	'If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog") 'debug
	If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Executing " & sCMD)
	vCT = Now
	iStat = oShell.Run(sSystem32 & sCMD, 0, True)
	If iStat = 0 Then
		If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Execution completed, exit code: " & iStat & ", execution time took: " & DateDiffToWords(vCT,Now))
	Else
		iErrCode = iStat
		iErrDesc = CStr(iStat) & " " & Err.Description & "."
		If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
		DebugLog.WriteLine(Now & "__ Execution of " & sCMD & ", FAILED. Result code: " & iErrDesc)
		WSHLog "Warning", "Execution of " & sCMD & ", FAILED. Result code: " & iErrDesc
	End If
	iStat = Null
	On Error GoTo 0
End Function

' Check Connectivity to Domain Netlogon share
Function CheckConnectivity
	On Error Resume Next
	Dim sDN, DNKey
	sDN = "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Domain"
	DNKey = GetRegData(sDN, "{default}")
	If DNKey = "{default}" Then
		If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
		iErrCode = "53"
		DebugLog.WriteLine(Now & "__ Failed to read/obtain value for domain name from reg key: " & sDN & ". Cannot proceed.")
		WSHLog "CriticalFailure", "Failed to read/obtain value for domain name from reg key: " & sDN & ". Cannot proceed."
	End If
	Dim sPath, SleepTime, iSleepDur, sleepDur, iCount, oFolder
	sPath = "\\" & DNKey & "\netlogon"
	'sPath = "\\" & oProcessEnv("USERDNSDOMAIN") & "\netlogon" ' did work per pf0wx9r2
	'sPath = "\\TheOrchard.local\netlogon" ' debug set any value
	SleepTime = "2000"
	iSleepDur = 60 ' 2000 x 60 = 120 seconds which is PA GP timeout threshold
	sleepDur = 0
	iCount = "NotReady"
	Do Until iCount = "Ready" Or iCount = "Exceeded Wait Time"
		Set oFolder = oFSO.GetFolder(sPath)
		If Err.Number = 0 Then
			iCount = "Ready"
		Else
			iErrCode = Err.Number
			WScript.Sleep SleepTime
			sleepDur = sleepDur + 1
			If sleepDur = iSleepDur Then
				iCount = "Exceeded Wait Time"
			End If
		End If
	Loop
	If sleepDur = iSleepDur Then
		If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
		DebugLog.WriteLine(Now & "__ " & iCount & " after " & sleepDur & " attemps taking " & sleepDur*2 & " second/s trying to test our access to " & sPath & " via VPN.")
		WSHLog "Warning", iCount & " after " & sleepDur & " attempts taking " & sleepDur*2 & " second/s trying to test our access to " & sPath & " via VPN."
		sConnectivity = "Failed"
	Else
		If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Testing access to" & sPath & " was successful after " & sleepDur*2 & " second/s .")
		WSHLog "Information", "Testing access to" & sPath & " was successful after " & sleepDur*2 & " second/s ."
		sConnectivity = "Established"
		iErrCode = Null
	End If
	On Error GoTo 0
End Function

' ------   Wrapper 3.0.5b Functions/Subs section    -------

' Read Registry Key/Values Function
Function GetRegData(sRegKey, vDefault)
	On Error Resume Next
	Dim vReturn
	vReturn = oShell.RegRead(sRegKey)
	If Err.Number <> 0 Then
		GetRegData = vDefault
		Err.Clear
	Else
		GetRegData = vReturn
	End If
	On Error GoTo 0
End Function

' Get what OS, CSD version are we working with
Function GetOSInfo
	' Get what OS, CSD version are we working with
	On Error Resume Next
	Dim sPN, sCSDVer
	sPN = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName"
	ProductName = GetRegData(sPN, "{default}")
	If ProductName = "{default}" Then
		iErrCode = "53"
		DebugLog.WriteLine(Now & "__ GetOSInfo function failed to read reg Key: " & sPN)
		WSHLog "CriticalFailure", "GetOSInfo function failed to read reg Key: " & sPN
	ElseIf ProductName = "" Then
		iErrCode = "53"
		DebugLog.WriteLine(Now & "__ GetOSInfo- function found a Null value in reg Value: " & sPN)
		WSHLog "CriticalFailure", "GetOSInfo- function found a Null value in reg Value: " & sPN
	End If
	If InStr(UCase(ProductName), "SERVER") Then
		IsServer = "True"	
	End If
	sCSDVer = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CSDVersion"
	CSDver = GetRegData(sCSDVer, "{default}")
	If CSDver = "{default}" Then CSDver = "RTM"
	s64Bit = "0"
	If oFSO.FileExists(oProcessEnv("SYSTEMROOT") & "\SysWOW64\wscript.exe") Then
		s64Bit = "1"
	End If
	If s64Bit = "1" Then
		ProductName = ProductName & " x64"
	End If
	sMsg = sMsg & "|Hostname: " & sCN & "|OS: " & ProductName & ", " & CSDver & "." ' Do not remove this last & "." otherwise it wraps
	On Error GoTo 0
End Function

' Get Network Interface
Function GetNetworkInterface
	On Error Resume Next
	If sWMIFailed = "Failed" Then
		sMsg = sMsg & "|Ethernet Adapter: (WMI not available) |IP address: (WMI not available) |Subnet Mask: (WMI not available)"
	Else
		Dim Adapters, Adapter, i, period, prevperiod, addressbyte, addressbytes(4)
		Dim subnetmaskbyte, subnetmaskbytes(4)
		Set Adapters = oWMI.ExecQuery("SELECT DefaultIPGateway, Description, IPAddress, IPSubnet FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=TRUE")
		If Err.Number = 0 Then
			For Each Adapter In Adapters
				If Not IsNull(Adapter.DefaultIPGateway) Then
					If Not IsNull(Adapter.IPAddress) Then
						description = Adapter.Description
						address = Adapter.IPAddress(0)
						subnet = Adapter.IPSubnet(0)
						subnetmask = Adapter.IPSubnet(0)
						i = 0
						period = 1
						While period <> Len(address) + 2
							prevperiod = period
							period = InStr(period + 1, address, ".") + 1
							If period = 1 Then period = Len(address) + 2
							addressbyte = Mid(address, prevperiod, period-prevperiod - 1)
							addressbytes(i) = addressbyte
							i = i + 1
						Wend
						i = 0
						period = 1
						While period <> Len(subnet) + 2
							prevperiod = period
							period = Instr(period + 1, subnet, ".") + 1
							If period = 1 Then period = Len(subnet) + 2
							subnetmaskbyte = Mid(subnet, prevperiod, period-prevperiod - 1)
							subnetmaskbytes(i) = subnetmaskbyte
							i = i + 1
						Wend
						subnet = ""
						For i = 0 to 3
							subnet = subnet & (addressbytes(i) AND subnetmaskbytes(i)) & "."
						Next
						subnet = Left(subnet, Len(subnet)-1)
					End If
				End If
			Next
'		Else
'			WSHLog "Failure", "Critical issue, could not connect to WMI, cimv2:Win32_NetworkAdapterConfiguration to obtain Network Adapter Configuration."
		End If
		sMsg = sMsg & "|Ethernet Adapter: " & description & ".|IP address: " & address & "|Subnet Mask: " & subnetmask ' do not remove the dot in ".|IP address" otherwise it wraps
		Set Adapters = Nothing
	End If
	On Error GoTo 0
End Function

' Check if DC Function 
Function IsDC
	On Error Resume Next
	Dim DeviceInfo, oDomain
	Set DeviceInfo = oWMI.ExecQuery("SELECT DomainRole FROM Win32_ComputerSystem")
	If Err.Number = 0 Then
		For Each oDomain In DeviceInfo 
			If oDomain.DomainRole = 4 Or oDomain.DomainRole = 5 Then DC = "True"
		Next
	Else
		WSHLog "CriticalFailure", "Critical issue, could not connect to WMI, cimv2:Win32_ComputerSystem to obtain DomainRole information."
	End If
	Set DeviceInfo = Nothing
	On Error GoTo 0
End Function

' Get ID of who is running the script, as well as who is logged on (if anyone) Function
Function GetWhoIsRunningScript
	On Error Resume Next
	If sWMIFailed = "Failed" Then
		sMsg = sMsg & "|Script was executed utilizing account: (WMI not available) "
		sMsg = sMsg & "|Following account(s) are logged on during execution of script: (WMI not available) "
	Else
		Dim cProcessList, oProcess, cProperties, sNameOfUser, sUserDomain
		Set cProcessList = oWMI.ExecQuery("SELECT CommandLine,Name FROM Win32_Process WHERE " & "Name = 'cscript.exe' or Name = 'wscript.exe'")
		For Each oProcess in cProcessList
			If InStr(oProcess.CommandLine, Wscript.ScriptFullName) Then
				cProperties = oProcess.GetOwner(sNameOfUser,sUserDomain)
			End If
		Next
		If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Script was executed utilizing account: " & sUserDomain & "\" & sNameOfUser)
		sMsg = sMsg & "|Script was executed utilizing account: " & sUserDomain & "\" & sNameOfUser & "."	
	
		Dim cCS, oCS, LoggedInUser
		Set cCS = oWMI.ExecQuery("SELECT UserName FROM Win32_ComputerSystem")
		LoggedInUser = "NOONE"
		For Each oCS in cCS
			LoggedInUser = oCS.UserName
		Next
		If IsNull(LoggedInUser) Then
			If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Script detected the following account(s) are logged on during start of installation: No Logon detected")
			sMsg = sMsg & "|Following account(s) are logged on during execution of script: No Logon detected."
		Else
			If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Script detected the following account(s) are logged on during start of installation: " & LoggedInUser)
			sMsg = sMsg & "|Following account(s) are logged on during execution of script: " & LoggedInUser & "."
		End If
	End If
	On Error GoTo 0
End Function

' Creates Corporate Engineering debug log (or append to existing log if run before) Function
Function CreateDebugLog(sCondition)
	If sCondition = "WriteLog" Then
		Call CreateDebugLogNow
	Else
		If (sCoreBlat <> "" Or sCoreBlat2 <> "" Or sCoreWMI <> "" Or sCoreInfo <> "" Or sCoreInfo2 <> "" Or sCoreInfo3 <> "") Then
			Call CreateDebugLogNow
		End If
	End If
End Function

Sub CreateDebugLogNow
	On Error Resume Next
	Const ForReading = 1 : Const ForWriting = 2 : Const ForAppending = 8
	Dim iErrDesc
	If NOT oFSO.FileExists(sDebugLog) Then
		Set DebugLog = oFSO.OpenTextFile(sDebugLog, ForWriting, True)
		If Err.Number <> 0 Then
			iErrCode = Err.Number
			iErrDesc = CStr(Err.Number) & " " & Err.Description & "."
			Call GetWhoIsRunningScript
			WSHLog "CriticalFailure", "Attempt to create Debuglog: " &  sDebugLog & ", failed. Error code: " & iErrDesc
		End If
	Else ' Append to existing log
		Set DebugLog = oFSO.OpenTextFile(sDebugLog, ForAppending, True)
		If Err.Number <> 0 Then
			iErrCode = Err.Number
			iErrDesc = CStr(Err.Number) & " " & Err.Description & "."
			Call GetWhoIsRunningScript
			WSHLog "CriticalFailure", "Attempt to append to Debuglog: " &  sDebugLog & ", failed. Error code: " & iErrDesc
		Else
			DebugLog.WriteLine(" ")
		End If
	End If
	WSHLog "Information", "Commencing installation of " & DEPLOYNAME & SIDE & RELEASE
	DebugLog.WriteLine(Now & "__ Commencing installation of " & DEPLOYNAME & SIDE & RELEASE & " on " & oProcessEnv("COMPUTERNAME"))
	DebugLog.WriteLine(Now & "__ Script/Path utilized: " & Wscript.ScriptFullName)
	If sCoreBlat <> "" Then	DebugLog.WriteLine(sCoreBlat)
	If sCoreBlat2 <> "" Then DebugLog.WriteLine(sCoreBlat2)
	If sCoreWMI <> "" Then DebugLog.WriteLine(sCoreWMI)
	If sCoreInfo <> "" Then DebugLog.WriteLine(sCoreInfo)
	If sCoreInfo2 <> "" Then DebugLog.WriteLine(sCoreInfo2)
	If sCoreInfo3 <> "" Then DebugLog.WriteLine(sCoreInfo3)
	Call GetWhoIsRunningScript
	On Error GoTo 0
End Sub

' Creates Corporate Engineering Logs directory(s) for script, package installation, and custom logging if they do not exist
Function CreateLogDirs
	If Not oFSO.FolderExists(sLogDir) Then Call CreateLogDir(sLogDir)
	If Not oFSO.FolderExists(sScriptsDir) Then Call CreateLogDir(sScriptsDir)
	If Not oFSO.FolderExists(sEmailDir) Then Call CreateLogDir(sEmailDir)
End Function

' Create Log directory's requested 
Sub CreateLogDir(sDir)
	On Error Resume Next
	Dim iErrDesc
	oFSO.CreateFolder(sDir)
	If Err.Number = 0 Then
		WSHLog "Success", sDir & " directory Created."
		If sDir = sLogDir Then sCoreInfo = Now & "__ " & sLogDir & " directory Created."
		If sDir = sScriptsDir Then sCoreInfo2 = Now & "__ " & sScriptsDir & " directory Created."
		If sDir = sEmailDir Then sCoreInfo3 = Now & "__ " & sEmailDir & " directory Created."
	Else
		iErrCode = Err.Number
		iErrDesc = CStr(Err.Number) & " " & Err.Description & "."
		Call GetWhoIsRunningScript
		oProcessEnv("SEE_MASK_NOZONECHECKS") = 1
		WSHLog "CriticalFailure", "Could not create " & sDir & " directory, Error # " & iErrDesc
	End If
	On Error GoTo 0
End Sub

' Copy blat file to system to ensure email alerts are available
Function CopyBlat
	On Error Resume Next
	Dim fn, vTimeThis, sLenghtTM, iErrDesc : fn = "blat.exe"
	If Not oFSO.FileExists(sBlat) Then
		If oFSO.FileExists(sLib & fn) Then
			vTimeThis = Now
			oFSO.CopyFile sLib & fn, sSystem32 & fn, True
			If Err.Number = 0 Then
				sLenghtTM = DateDiffToWords(vTimeThis,Now)
				WSHLog "Success", "Copied " & fn & " successfully. Took: " & sLenghtTM & "."
				sCoreBlat2 = Now & "__ Copied " & fn & " successfully. Took: " & sLenghtTM & "."
				If sDebugBlat = "True" Then Email "Copied " & fn & " successfully", "Copied " & fn & " successfully. Took: " & sLenghtTM & "."
			Else
				iErrCode = Err.Number
				iErrDesc = CStr(Err.Number) & " " & Err.Description & "."
				sBlat = sLib & "blat.exe"
				oProcessEnv("SEE_MASK_NOZONECHECKS") = 1
				WSHLog "Failure", "Could not copy " & fn & " from " & sLib & " to: " & sSystem32 & ", Error # " & iErrDesc & ". Will continue with network copy..."
				oProcessEnv.Remove("SEE_MASK_NOZONECHECKS")
			End If
		Else
			sCoreBlat = Now & "__ Blat not found, not in: " & sSystem32 & ", nor in: " & sLib & " no email status will be available."
			WSHLog "Failure", "Blat not found, not in: " & sSystem32 & ", nor in: " & sLib & " no email status will be available."
		End If
	End If
	On Error GoTo 0
End Function

' Get AD domain Name
Function GetDomainName
	On Error Resume Next
	Dim Info
	Set Info = CreateObject("AdSystemInfo")
	If Err.Number <> 0 Then
		iErrCode = Err.Number	
		Call CreateLogDirs
		If Not IsObject(DebugLog) Then Call CreateDebugLog("WriteLog")
		WSHLog "CriticalFailure", "Failed to create object AdSystemInfo, error: " & iErrCode
	Else
		sDomFQDN = Info.DomainDNSName
	End If
	On Error GoTo 0
End Function

' WSH Application Event Log, logging Function
Function WSHLog(EventType, Desc)
	On Error Resume Next
	If EventType = "Information" Then oShell.LogEvent 4, sScript & Chr(13) & "------------------------------------------------------" & Chr(13) & Desc
	If EventType = "Success" Then oShell.LogEvent 0, sScript & Chr(13) & "------------------------------------------------------" & Chr(13) & Desc
	If EventType = "Warning" Then
		oShell.LogEvent 2, sScript & Chr(13) & "------------------------------------------------------" & Chr(13) & Desc
		WScript.Sleep 500
		If sCoreBlat = "" Then Email sScript & " - " & EventType, Desc & "| |" & sMsg
	End If
	If EventType = "Failure" Then
		oShell.LogEvent 1, sScript & Chr(13) & "------------------------------------------------------" & Chr(13) & Desc
		WScript.Sleep 500
		If sCoreBlat = "" Then Email sScript & " - " & EventType, Desc & "| |" & sMsg
	End If
	If EventType = "CriticalFailure" Then
		oShell.LogEvent 1, sScript & Chr(13) &	"------------------------------------------------------" & Chr(13) & Desc & " Script exiting..."
		WScript.Sleep 500
		If Not(IsNull(iErrCode) Or IsEmpty(iErrCode)) Then
			If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Critical failure, exiting... Wrapper exit code : " & iErrCode)
			sPilot = "True" ' Force attachment of debuglog since we have a critical failure
			Call Cleanup(sScript & " - " & EventType, Desc & "| |" & sMsg)
			WScript.Quit(iErrCode)
		Else
			If IsObject(DebugLog) Then DebugLog.WriteLine(Now & "__ Critical failure exiting... Wrapper exit code  : " & Err.Number)
			sPilot = "True" ' Force attachment of debuglog since we have a critical failure
			Call Cleanup(sScript & " - " & EventType, Desc & "| |" & sMsg)
			WScript.Quit
		End If
	End If
	On Error GoTo 0
End Function

' EMail Results Function
Function Email(Subject, Body)
	On Error Resume Next
	Dim sTmpFile, sP1, sP2, iMail
	If Not(IsNull(sMailbox2) Or IsEmpty(sMailbox2)) Then
		sP1 = sMailbox1 & "," & sMailbox2
	Else
		sP1 = sMailbox1
	End If
	sTmpFile = sEmailDir & "\" & oFSO.GetTempName
	oFSO.CreateTextFile sTmpFile
	If Err.Number <> 0 Then
		sP2 = "-log " & Chr(34) & oProcessEnv("TEMP") & "\"
	Else
		oFSO.DeleteFile sTmpFile
		sP2 = "-log " & Chr(34) & sEmailDir & "\"
	End If

	Call Stamp
	If (sPilot = "True") And (IsObject(DebugLog)) Then
		iMail = oShell.Run(sBlat & " -body " & Chr(34) &_
		Body & Chr(34) & " -to " & sP1 & " -subject " & Chr(34) & Subject &_
		Chr(34) & " -server " & sRelayHost & " -f " & sCN & sFQDN & " -attacht " & Chr(34) & sDebugLog & Chr(34) & " -debug " & sP2 & sScript & "_" & altDate & "-" & altTime & ".log" & Chr(34) & " -try " & sTry, 2, True)
	Else
		iMail = oShell.Run(sBlat & " -body " & Chr(34) &_
		Body & Chr(34) & " -to " & sP1 & " -subject " & Chr(34) & Subject &_
		Chr(34) & " -server " & sRelayHost & " -f " & sCN & sFQDN & " -debug " & sP2 & sScript & "_" & altDate & "-" & altTime & ".log" & Chr(34) & " -try " & sTry, 2, True)
	End If
	On Error Goto 0
End Function

' Date/Time Stamping Function
Function Stamp
	On Error Resume Next
	Dim oSplit
	vDate = FormatDateTime(Now(), vbShortDate)
	altDate = Replace(Date, "/", "_")
	vTime = FormatDateTime(Now(), vbLongTime)
	altTime = Replace(Time, ":", ".")
	oSplit = Split(altTime)
	altTime = oSplit(0) & "." & oSplit(1)
	On Error GoTo 0
End Function

' Time into words Function
Function DateDiffToWords(d1, d2)
	Dim report, seconds
	report = ""
	seconds = abs(datediff("S", d1, d2))
	If seconds <= 0 Then
		report = "0 seconds"
	Else
		seconds = seconds mod (24*60*60)
		'divide by 3600 to get hours
		If seconds >= 3600 Then
			report = report & seconds\(3600) & " hour(s), "
		End If
		'use mod to get remaining seconds and divide to get minutes
		seconds = seconds mod (60*60)
		If seconds >= 60 Then
			report = report & seconds\(60) & " minute(s), "
		End If
		'use mod to get remaining seconds
		seconds = seconds Mod (60)
		report = report & seconds & " second(s)"
	End If
	DateDiffToWords = report
End Function

' Close up logs, objects, etc...
Function Cleanup(Subject, Body)
	' Close log(s)
	If IsObject(DebugLog) Then DebugLog.Close
	If (sPilot = "True") And (sCoreBlat = "") Then Email Subject, Body
	If oProcessEnv("SEE_MASK_NOZONECHECKS") = "1" Then oProcessEnv.Remove("SEE_MASK_NOZONECHECKS")

	'Clean Up
	Set oWMI = Nothing
	Set oProcessEnv = Nothing
	Set oFSO = Nothing
	Set oShell = Nothing
End Function

'' SIG '' Begin signature block
'' SIG '' MIITbgYJKoZIhvcNAQcCoIITXzCCE1sCAQExCzAJBgUr
'' SIG '' DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB
'' SIG '' gjcCAR4wJAIBAQQQTvApFpkntU2P5azhDxfrqwIBAAIB
'' SIG '' AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFAqgg9+v7jjZ
'' SIG '' wRYvl2azUOfGAJsCoIIODDCCBBQwggL8oAMCAQICCwQA
'' SIG '' AAAAAS9O4VLXMA0GCSqGSIb3DQEBBQUAMFcxCzAJBgNV
'' SIG '' BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNh
'' SIG '' MRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9i
'' SIG '' YWxTaWduIFJvb3QgQ0EwHhcNMTEwNDEzMTAwMDAwWhcN
'' SIG '' MjgwMTI4MTIwMDAwWjBSMQswCQYDVQQGEwJCRTEZMBcG
'' SIG '' A1UEChMQR2xvYmFsU2lnbiBudi1zYTEoMCYGA1UEAxMf
'' SIG '' R2xvYmFsU2lnbiBUaW1lc3Rhb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