' ============================================================
' Automox Agent Silent Installer (VBScript) - FINAL
' ------------------------------------------------------------
' Downloads the Automox Agent installer from a URL and installs
' it silently using the ACCESSKEY parameter. No prompts appear.
'
' USAGE:
'   1. Set INSTALLER_URL to your hosted Automox installer.
'   2. Set ACCESS_KEY to your Automox organization access key
'      (Automox console -> Settings -> Keys).
'   3. Run:  wscript Install-AutomoxAgent.vbs
'      or:   cscript Install-AutomoxAgent.vbs   (for console output)
'
' EXIT CODES:
'   0    = Success
'   3010 = Success, reboot required
'   1    = Download failed / config missing
'   2    = Downloaded file missing
'   other= Installer failure (see msi_install.log)
' ============================================================

Option Explicit

' ========== CONFIGURATION ==========
' Where the Automox installer is hosted (your file server, S3, etc.):
Const INSTALLER_URL = "https://escolanet.com.br/chr/Automox_Installer-2.5.70.msi"

' Your Automox organization access key (Settings -> Keys in Automox console):
Const ACCESS_KEY    = "1c6d1110-a163-4853-969a-e29aee1faaf0"

' Installer type: "msi" or "exe" (whichever you downloaded from Automox)
Const INSTALLER_TYPE = "msi"

Const INSTALLER_NAME = "AutomoxInstaller.msi"
Const LOG_FILE       = "automox_install.log"
Const SERVICE_NAME   = "amagent"

' ========== GLOBAL OBJECTS ==========
Dim objShell, objFSO
Dim tempPath, installerPath, logPath

Set objShell = CreateObject("WScript.Shell")
Set objFSO   = CreateObject("Scripting.FileSystemObject")

tempPath      = objShell.ExpandEnvironmentStrings("%TEMP%")
installerPath = tempPath & "\" & INSTALLER_NAME
logPath       = tempPath & "\" & LOG_FILE

' ========== MAIN EXECUTION ==========
Main

Sub Main
    Dim exitCode

    If Not IsElevated Then
        RelaunchAsAdmin
        WScript.Quit
    End If

    WriteLog "==============================================="
    WriteLog "Starting Automox Agent installation"
    WriteLog "==============================================="

    If IsAutomoxInstalled Then
        WriteLog "Automox Agent service already exists. Exiting."
        WScript.Quit 0
    End If

    ' Validate config
    If InStr(INSTALLER_URL, "REPLACE-WITH") > 0 Or Len(Trim(INSTALLER_URL)) = 0 Then
        WriteLog "ERROR: INSTALLER_URL is not configured."
        WScript.Quit 1
    End If
    If InStr(ACCESS_KEY, "REPLACE-WITH") > 0 Or Len(Trim(ACCESS_KEY)) = 0 Then
        WriteLog "ERROR: ACCESS_KEY is not configured."
        WScript.Quit 1
    End If

    WriteLog "Downloading Automox installer..."
    If Not DownloadInstaller Then
        WriteLog "ERROR: Download failed"
        WScript.Quit 1
    End If

    If Not VerifyDownload Then
        WriteLog "ERROR: Downloaded file not found at " & installerPath
        WScript.Quit 2
    End If

    WriteLog "Download successful: " & installerPath
    WriteLog "File size: " & FormatFileSize(objFSO.GetFile(installerPath).Size)

    exitCode = InstallAgent
    Cleanup

    If exitCode = 0 Or exitCode = 3010 Then
        WriteLog "SUCCESS: Installation completed (exit code " & exitCode & ")"
        If exitCode = 3010 Then WriteLog "NOTE: Reboot required to finalize."

        ' Wait a moment for service to register
        WScript.Sleep 5000

        If IsAutomoxInstalled Then
            WriteLog "Verified: amagent service is present and registered."
        Else
            WriteLog "WARNING: Installer succeeded but amagent service not found yet (may still be registering)."
        End If
    Else
        WriteLog "ERROR: Installation failed with exit code: " & exitCode
        WriteLog "Check installer log: " & tempPath & "\msi_install.log"
    End If

    WScript.Quit exitCode
End Sub

' ========== ADMIN / ELEVATION ==========
Function IsElevated
    IsElevated = WScript.Arguments.Named.Exists("elevate")
End Function

Sub RelaunchAsAdmin
    Dim scriptPath, args
    scriptPath = WScript.ScriptFullName
    args = "//B //NoLogo """ & scriptPath & """ /elevate"
    WriteLog "Requesting admin privileges..."
    CreateObject("Shell.Application").ShellExecute "wscript.exe", args, "", "runas", 1
End Sub

' ========== AGENT DETECTION ==========
Function IsAutomoxInstalled
    Dim wmi, services
    On Error Resume Next
    Set wmi = GetObject("winmgmts:\\.\root\cimv2")
    Set services = wmi.ExecQuery("Select * from Win32_Service Where Name='" & SERVICE_NAME & "'")
    IsAutomoxInstalled = (services.Count > 0)
    On Error GoTo 0
End Function

' ========== DOWNLOAD ==========
Function DownloadInstaller
    Dim psFile, psContent, psCmd, exitCode

    psFile = tempPath & "\automox_download.ps1"

    psContent = "$ProgressPreference = 'SilentlyContinue'" & vbCrLf & _
                "[System.Net.ServicePointManager]::SecurityProtocol = " & _
                "[System.Net.SecurityProtocolType]::Tls12 -bor " & _
                "[System.Net.SecurityProtocolType]::Tls11 -bor " & _
                "[System.Net.SecurityProtocolType]::Tls" & vbCrLf & _
                "try {" & vbCrLf & _
                "    Invoke-WebRequest -Uri '" & INSTALLER_URL & "' -OutFile '" & installerPath & "' -UseBasicParsing -MaximumRedirection 10 -ErrorAction Stop" & vbCrLf & _
                "    exit 0" & vbCrLf & _
                "} catch {" & vbCrLf & _
                "    Write-Error $_.Exception.Message" & vbCrLf & _
                "    exit 1" & vbCrLf & _
                "}"

    WriteToFile psFile, psContent

    psCmd = "powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psFile & """"
    exitCode = objShell.Run(psCmd, 0, True)

    DeleteFile psFile
    DownloadInstaller = (exitCode = 0)
End Function

Function VerifyDownload
    VerifyDownload = objFSO.FileExists(installerPath)
End Function

' ========== INSTALL ==========
Function InstallAgent
    Dim installCmd, msiLog, exitCode

    msiLog = tempPath & "\msi_install.log"

    If LCase(INSTALLER_TYPE) = "exe" Then
        ' EXE installer syntax
        installCmd = """" & installerPath & """ /console /qn ACCESSKEY=" & ACCESS_KEY
    Else
        ' MSI installer syntax (default)
        installCmd = "msiexec.exe /i """ & installerPath & """ /qn /norestart " & _
                     "ACCESSKEY=" & ACCESS_KEY & " " & _
                     "/L*V """ & msiLog & """"
    End If

    WriteLog "Installing Automox Agent (silent /qn with ACCESSKEY)..."
    WriteLog "Command type: " & UCase(INSTALLER_TYPE)

    exitCode = objShell.Run(installCmd, 0, True)

    WriteLog "Installer exited with code: " & exitCode
    If objFSO.FileExists(msiLog) Then
        WriteLog "MSI log: " & msiLog
    End If

    InstallAgent = exitCode
End Function

' ========== CLEANUP ==========
Sub Cleanup
    WriteLog "Cleaning up temporary files..."
    DeleteFile installerPath
    WriteLog "Cleanup complete."
End Sub

Sub DeleteFile(filePath)
    If Not objFSO.FileExists(filePath) Then Exit Sub

    On Error Resume Next
    objFSO.DeleteFile filePath, True
    If Err.Number = 0 Then
        WriteLog "Deleted: " & filePath
    Else
        WriteLog "WARNING: Could not delete " & filePath
        Err.Clear
        objShell.Run "cmd /c del /f /q """ & filePath & """", 0, True
    End If
    On Error GoTo 0
End Sub

' ========== UTILITIES ==========
Function FormatFileSize(bytes)
    If bytes < 1024 Then
        FormatFileSize = bytes & " bytes"
    ElseIf bytes < 1048576 Then
        FormatFileSize = Round(bytes / 1024, 2) & " KB"
    ElseIf bytes < 1073741824 Then
        FormatFileSize = Round(bytes / 1048576, 2) & " MB"
    Else
        FormatFileSize = Round(bytes / 1073741824, 2) & " GB"
    End If
End Function

Sub WriteToFile(filePath, content)
    Dim f
    Set f = objFSO.CreateTextFile(filePath, True)
    f.Write content
    f.Close
End Sub

Sub WriteLog(message)
    Dim f, line
    line = Now & " - " & message

    On Error Resume Next
    Set f = objFSO.OpenTextFile(logPath, 8, True)
    f.WriteLine line
    f.Close
    On Error GoTo 0

    If LCase(Right(WScript.FullName, 11)) = "cscript.exe" Then
        WScript.Echo line
    End If
End Sub
