' FleetDeck-Deploy.vbs
' Adapted from TacticalRMM installer script for FleetDeck deployments.
'
' FleetDeck difference: the per-Deployment installer downloaded from the
' FleetDeck console already contains the client/site binding, so there is
' NO separate registration step (no --api / --auth / --client-id needed).
' You only need the download link of your Deployment.
'
Option Explicit

' ================= CONFIG =================
' Create a "Deployment" in the FleetDeck console (Agents > Deployments),
' copy its installer download link and paste it here.
Const DOWNLOAD_URL = "https://agent.fleetdeck.io/S9rGMsTRJNfJ6GV1AXNzxv?win"

Const SAVE_PATH    = "C:\Windows\Temp\fleetdeck-agent.exe"
Const AGENT_DIR    = "C:\Program Files (x86)\FleetDeck Agent"
Const SVC_NAME     = "FleetDeck Agent Service"
' ==========================================

Dim shell, fso, LOG_PATH

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

LOG_PATH = shell.ExpandEnvironmentStrings("%TEMP%") & "\fleetdeck-log.txt"

On Error Resume Next
Main
If Err.Number <> 0 Then
    Log "FATAL: " & Err.Description & " (0x" & Hex(Err.Number) & ")"
End If
WScript.Quit

Sub Log(msg)
    On Error Resume Next
    Dim f
    Set f = fso.OpenTextFile(LOG_PATH, 8, True)
    f.WriteLine Now & " - " & msg
    f.Close
End Sub

Function RunSilent(cmd)
    On Error Resume Next
    RunSilent = shell.Run(cmd, 0, True)
    If Err.Number <> 0 Then
        Log "Run failed (" & Err.Number & "): " & cmd
        RunSilent = -1
    End If
End Function

Function IsAdmin()
    IsAdmin = (RunSilent("net session") = 0)
End Function

Function ServiceRunning()
    ' sc query returns 0 if the service exists (running or stopped)
    ServiceRunning = (RunSilent("sc query """ & SVC_NAME & """") = 0)
End Function

Sub Main()
    Log "=== started (admin=" & IsAdmin() & ") ==="

    ' ---- Elevation: relaunch hidden, only if not already admin ----
    If Not IsAdmin() Then
        Dim htaPath
        htaPath = WScript.ScriptFullName
        If htaPath = "" Then
            Log "ERROR: could not resolve own .vbs path"
            WScript.Quit
        End If
        Log "Relaunching elevated (hidden): " & htaPath
        On Error Resume Next
        Dim sa
        Set sa = CreateObject("Shell.Application")
        sa.ShellExecute "wscript.exe", """" & htaPath & """", "", "runas", 0
        If Err.Number <> 0 Then
            Log "Elevation declined/failed: " & Err.Description
            WScript.Quit
        End If
        WScript.Sleep 2000
        WScript.Quit
    End If

    ' ---- Elevated: all silent from here ----

    ' ---- Already installed? FleetDeck skips a reinstall of the same
    '      Deployment anyway, but we avoid a needless download. ----
    If ServiceRunning() Or fso.FolderExists(AGENT_DIR) Then
        Log "Agent already present - starting service."
        RunSilent "sc start """ & SVC_NAME & """"
        Log "=== complete (already installed) ==="
        WScript.Sleep 1000
        WScript.Quit
    End If

    Log "Downloading FleetDeck deployment installer..."
    On Error Resume Next

    If Not fso.FolderExists("C:\Windows\Temp") Then fso.CreateFolder("C:\Windows\Temp")
    If fso.FileExists(SAVE_PATH) Then fso.DeleteFile SAVE_PATH, True

    Dim http
    Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    http.setTimeouts 30000, 30000, 30000, 300000
    http.open "GET", DOWNLOAD_URL, False
    http.send

    If http.status <> 200 Then
        Log "ERROR: download HTTP " & http.status
        WScript.Quit
    End If

    Dim stream
    Set stream = CreateObject("ADODB.Stream")
    stream.Type = 1
    stream.Open
    stream.Write http.responseBody
    stream.SaveToFile SAVE_PATH, 2
    stream.Close

    Log "Download complete (" & Round(fso.GetFile(SAVE_PATH).Size / 1024) & " KB)."

    ' ---- Install silently. The Deployment installer self-registers with
    '      the correct FleetDeck account/client/site - no extra flags. ----
    Log "Installing silently..."
    Dim ins
    ins = RunSilent("""" & SAVE_PATH & """ -silent")
    Log "Installer exit code: " & ins

    If Not (fso.FolderExists(AGENT_DIR) Or ServiceRunning()) Then
        Log "ERROR: FleetDeck Agent not found after install (exit " & ins & ")"
        WScript.Quit
    End If

    Log "FleetDeck Agent installed - starting service..."
    RunSilent "sc start """ & SVC_NAME & """"

    ' ---- Cleanup ----
    On Error Resume Next
    If fso.FileExists(SAVE_PATH) Then fso.DeleteFile SAVE_PATH, True

    Log "=== complete ==="
    WScript.Sleep 1000
End Sub