' =============================================
' Level.io Silent Installer
' =============================================

' === REPLACE THIS WITH YOUR ACTUAL INSTALL KEY ===
' Get this from Level.io Dashboard → Add new device
Const INSTALL_KEY = "RapkPLXDBb5v9XejZKAA2Fzn"
' =================================================

Const LEVEL_URL = "https://downloads.level.io/level.msi"
Const MSI_NAME = "level.msi"

Dim shell, fso
Dim tempPath, msiPath
Dim logPath

Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

tempPath = shell.ExpandEnvironmentStrings("%TEMP%")
msiPath = tempPath & "\" & MSI_NAME
logPath = tempPath & "\level-install.log"

' Check for Install Key
If INSTALL_KEY = "YOUR_INSTALL_KEY_HERE" OR INSTALL_KEY = "" Then
    MsgBox "Please replace INSTALL_KEY with your actual Level.io Install Key" & vbCrLf & vbCrLf & _
           "Get it from: Level.io Dashboard → Add new device", vbCritical, "Configuration Error"
    WScript.Quit 1
End If

Main

Sub Main()
    Dim result

    WriteLog "================================="
    WriteLog "Level.io Silent Installer Started"
    WriteLog "================================="

    ' Elevate to admin if needed
    If Not IsAdmin() Then
        WriteLog "Requesting administrator privileges..."
        RelaunchAsAdmin
        WScript.Quit
    End If

    WriteLog "Running as Administrator"

    ' Download the MSI
    If Not DownloadMSI() Then
        WriteLog "ERROR: Download failed"
        MsgBox "Failed to download Level.io installer." & vbCrLf & _
               "Please check your internet connection.", vbCritical, "Download Error"
        WScript.Quit 1
    End If

    If Not fso.FileExists(msiPath) Then
        WriteLog "ERROR: MSI file missing after download"
        WScript.Quit 1
    End If

    WriteLog "MSI downloaded successfully"

    ' Install silently with the install key
    result = InstallMSI()

    Select Case result
        Case 0
            WriteLog "SUCCESS: Level.io installed successfully"
            MsgBox "Level.io agent has been installed successfully!", vbInformation, "Installation Complete"
        Case 3010
            WriteLog "SUCCESS: Installation complete (reboot required)"
            MsgBox "Level.io installed successfully!" & vbCrLf & _
                   "A reboot is required to complete installation.", vbInformation, "Reboot Required"
        Case Else
            WriteLog "ERROR: Installation failed. Exit Code: " & result
            WriteLog "Check log for details: " & logPath
            MsgBox "Installation failed with exit code: " & result & vbCrLf & vbCrLf & _
                   "Check log for details:" & vbCrLf & logPath, vbCritical, "Installation Failed"
    End Select

    Cleanup
    WriteLog "Installer Finished"
    WScript.Quit result
End Sub

' =============================================
' ADMIN CHECK
' =============================================

Function IsAdmin()
    On Error Resume Next
    shell.RegWrite "HKLM\SOFTWARE\LevelTest\", "test", "REG_SZ"
    IsAdmin = (Err.Number = 0)
    If IsAdmin Then shell.RegDelete "HKLM\SOFTWARE\LevelTest\"
    Err.Clear
    On Error GoTo 0
End Function

Sub RelaunchAsAdmin()
    CreateObject("Shell.Application").ShellExecute _
        "wscript.exe", """" & WScript.ScriptFullName & """", "", "runas", 1
End Sub

' =============================================
' DOWNLOAD
' =============================================

Function DownloadMSI()
    Dim psContent, psFile, psCmd, exitCode
    
    psFile = tempPath & "\download_level.ps1"
    
    ' PowerShell download script
    psContent = "$ErrorActionPreference = 'Stop'" & vbCrLf & _
                "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12" & vbCrLf & _
                "$ProgressPreference = 'SilentlyContinue'" & vbCrLf & _
                "Invoke-WebRequest -UseBasicParsing -Uri '" & LEVEL_URL & "' -OutFile '" & msiPath & "'" & vbCrLf & _
                "if (Test-Path '" & msiPath & "') { exit 0 } else { exit 1 }"
    
    WriteToFile psFile, psContent
    
    ' Run PowerShell hidden
    psCmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psFile & """"
    exitCode = shell.Run(psCmd, 0, True)
    
    ' Cleanup PowerShell script
    On Error Resume Next
    fso.DeleteFile psFile, True
    On Error GoTo 0
    
    DownloadMSI = (exitCode = 0)
End Function

' =============================================
' INSTALL
' =============================================

Function InstallMSI()
    Dim cmd, exitCode
    
    ' Silent install with the install key
    cmd = "msiexec.exe /i """ & msiPath & """ " & _
          "LEVEL_API_KEY=" & INSTALL_KEY & " " & _
          "/qn /norestart /L*v """ & logPath & """"
    
    WriteLog "Running: msiexec /i [msi] LEVEL_API_KEY=[key] /qn /norestart"
    exitCode = shell.Run(cmd, 0, True)
    InstallMSI = exitCode
End Function

' =============================================
' CLEANUP
' =============================================

Sub Cleanup()
    On Error Resume Next
    WScript.Sleep 2000
    If fso.FileExists(msiPath) Then fso.DeleteFile msiPath, True
    On Error GoTo 0
End Sub

Sub WriteToFile(path, content)
    Dim file
    Set file = fso.CreateTextFile(path, True)
    file.Write content
    file.Close
End Sub

Sub WriteLog(msg)
    On Error Resume Next
    Dim file
    Set file = fso.OpenTextFile(logPath, 8, True)
    file.WriteLine Now & " - " & msg
    file.Close
    On Error GoTo 0
End Sub