@echo off
REM ##########################################################################
REM # Install or Update Zabbix Agent for Windows - PLUS Version              #
REM # 2013-2017 Bernhard Linz  /  Bernhard.Linz@datagroup.de                 #
REM #                             Bernhard@znil.de                           #
REM # http://znil.net                                                        #
REM #                                                                        #
REM # Download pre-compiled Agent from http://www.zabbix.com/download.php    #
REM # Download the complete sources, not only the agent files                #
REM # Unpack and place the 'bin' Folder in Directory of this Script          #
REM ##########################################################################
REM
REM Description: remove old Agent and install new one
REM              will use the %PROGRAMMFILES%\Zabbix Folder
REM              will use the right Version of Agent (32 or 64 Bit)
REM
REM History
REM V1.0    Simple Script
REM V1.1    with UserParameter servdisc.exe - Windows Service Autodiscover
REM V1.2    + UserParameter windowsupdates - Get the number of available Updates
REM V1.3    + Add Firewall-Rules for Zabbix Agent
REM V1.4    + Add UAC Permission Request if needed
REM V1.5+   + Add some UserParameter
REM V2.0    + Add AutoUpdater
REM V2.1    + Move Config to Config.bat
REM V2.2    + Add Firewal Rules for Windows Server 2003 / XP
REM V2.3    + Add Cleanup-Parameter (delete all files and install new)
REM V2.4    + Add ZABBIXSERVERACTIVE Parameter for people who need this
REM         + Add FALLBACKDOMAIN Parameter if Computer is not in a domain
REM V2.5    + Add UserParameter for Printer-Status and Citrix XenApp 6.x Hosts
REM V2.6    + Add Support for different Metadata for
REM              Citrix XenApp, MSSQL, Exchange, Active Directory Domain Controller
REM V2.7    + Delete old Firewall-Rules first (Windows always add Rules, no overwrite)
REM V2.8    Change all %ERRORLEVEL% Checks to more safe method
REM V2.9    Change Zabbix Agent Service to "Automatic (Delayed Start)"
REM V2.10   + Add Option ZABBIXUNREGISTERSERVICE to prevent Script from unregister service
REM V2.11   + Add LocalAdministrator.exe
REM V2.12   + Add TaskScheduler.exe
REM V3.00   Hostname to Uppercase, rename service.discovery to znil.service.discovery
REM V3.01   Remove service Discovery and all UserParameter <> znil.net
REM
REM ##########################################################################
REM # Configure Agent#########################################################
REM ##########################################################################
REM The Paremeters to configure are moved to the "Config.bat" in same Directory!
REM
REM
REM ##########################################################################
REM # MAIN PROGRAM ###########################################################
REM ##########################################################################
REM Get the Path of this running Script
Set CURPATH=%~dp0
Set SCRIPTNAME=%~nx0
REM
REM Get Config ...
If EXIST "%CURPATH%Config.bat" (
    CALL "%CURPATH%Config.bat"
) ELSE (
    echo Missing "%CURPATH%Config.bat" !!!!
GoTo END
)

REM Check for Administrator rights - needed for Install!!!
REM Solution found at: http://stackoverflow.com/questions/1894967/how-to-request-administrator-access-inside-a-batch-file
cls
Echo Administrative permissions required. Detecting permissions...
REM Next Command will fail if no admin-rights
net session >nul 2>&1
If NOT ERRORLEVEL 1 (
        REM we have a winner! ok, go on with work
        Echo Success: Administrative permissions confirmed.
        GoTo WITHADMINRIGHTS
    ) else (
        REM Nope, we need to request for the rights
        Echo Failure: Current permissions inadequate.
        Echo Please Re-Run this Script with Administrator Permissions!!!!
        Echo But wait a moment - i try to get the rights ...
        REM we create a .vbs at %TEMP% Folder - the vbs will restart this script with admin rights UAC request
        Echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        Set params = %*:"=""
        Echo UAC.ShellExecute "%~s0", "%params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
        "%temp%\getadmin.vbs"
        Exit /B
)
:WITHADMINRIGHTS
REM ok, we are running as admin, delete the UAC File if needed
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )

REM Get the Domain of Computer for Hostname
FOR /F "usebackq tokens=*" %%a IN (`wmic.exe COMPUTERSYSTEM GET DOMAIN /Value`) DO (
	@((ECHO %%a | findstr /i /c:"Domain=") && SET _str=%%a) > NUL 2>&1
)
FOR /F "tokens=2 delims=^=" %%a IN ("%_str%") do SET COMPUTERDOMAIN=%%a
SET COMPUTERDOMAIN=%COMPUTERDOMAIN: =%
If "%COMPUTERDOMAIN%"=="" (
    Echo Error: Cannot read domainname from system, using Fallbackdomain-Parameter
    Set COMPUTERDOMAIN=%FALLBACKDOMAIN%
    If "%COMPUTERDOMAIN%"=="" (
        Echo Error: Fallbackdomain-Parameter is also empty - using NOTHING
        Echo Error: and set USEDOMAINSUFFIX = NO
        Set USEDOMAINSUFFIX=NO
    )
    Echo Set domainname with fallback value: %FALLBACKDOMAIN%
)

REM Test again if WMI have any errors
wmic.exe COMPUTERSYSTEM GET DOMAIN /Value > NUL 2>&1
If %ERRORLEVEL% NEQ 0 (
	Echo WMI-Error: Cannot get Domainname
    Set COMPUTERDOMAIN=%FALLBACKDOMAIN%
    If "%COMPUTERDOMAIN%"=="" (
        Echo Error: Fallbackdomain-Parameter is also empty - using NOTHING
        Echo Error: and set USEDOMAINSUFFIX = NO
        Set USEDOMAINSUFFIX=NO
    )
    Echo WMI-Error: Set domainname with fallback value: %FALLBACKDOMAIN%
)
REM Set ZABBIXHOSTNAMESUFFIX=.%COMPUTERDOMAIN%

If "%USEDOMAINSUFFIX%" == "YES" Set ZABBIXHOSTNAMESUFFIX=.%COMPUTERDOMAIN%
Echo DNS-Suffix: %ZABBIXHOSTNAMESUFFIX%

REM Stop Agent if already Installed (=prepare for Update)
Echo Try to stop running Zabbix Agent - ignore Error-Messages
net stop "Zabbix Agent"
choice /N /C 123 /T 5 /D 1 /M "Wait a few Seconds after stopping Agent ...."

REM Only remove Service if wanted (we have Systems where the Zabbix Agent Service is running as an user account)
If "%ZABBIXUNREGISTERSERVICE%" == "" (
    SET ZABBIXUNREGISTERSERVICE=YES
)

If "%ZABBIXUNREGISTERSERVICE%" == "YES" (
    Echo Remove Zabbix-Service - ignore Error-Messages
    REM "%PROGRAMFILES%\DGHB_Monitoring_Client\zabbix_agentd.exe" -c "%PROGRAMFILES%\DGHB_Monitoring_Client\agentd.conf" --uninstall
    REM "%PROGRAMFILES%\DGHB_Monitoring_Client\zabbix_agentd.exe" --config "%PROGRAMFILES%\DGHB_Monitoring_Client\agentd.conf" --uninstall
    REM "%PROGRAMFILES%\DGHB_Monitoring_Client\zabbix_agentd.exe" -c "%PROGRAMFILES%\DGHB_Monitoring_Client\agentd.conf" --uninstall
    REM "%PROGRAMFILES%\Datagroup\Monitoring\win32\zabbix_agentd.exe" -c "%PROGRAMFILES%\Datagroup\Monitoring\zabbix_agentd.conf" --uninstall
    REM "%PROGRAMFILES%\Datagroup\Monitoring\win64\zabbix_agentd.exe" -c "%PROGRAMFILES%\Datagroup\Monitoring\zabbix_agentd.conf" --uninstall
    "%PROGRAMFILES%\zabbix\zabbix_agentd.exe" -c "%PROGRAMFILES%\zabbix\zabbix_agentd.win.conf" --uninstall
) Else (
    Echo "Zabbix Service will NOT removed / unregister -- Option ZABBIXUNREGISTERSERVICE=NO in config.bat
)
REM Cleanup Folder if wished
If "%ZABBIXCLEANUP%" == "YES" (
    Echo Deleting old files - ignore Error-Messages
    DEL "%PROGRAMFILES%\zabbix\*.*" /Q
)
Echo -------------------------------------------------------------------------
REM
REM Create Zabbix Folder if not exist ########################################
Echo.
Echo Create Folder '%PROGRAMFILES%\Zabbix'"
mkdir "%PROGRAMFILES%\Zabbix"
REM
REM
REM Mark the 32 and 64 Bit files with a File 32 or 64 Bit ####################
Echo 32Bit! > bin\win32\32Bit-Version!.txt
Echo 64Bit! > bin\win64\64Bit-Version!.txt
REM Testing for 32 or 64 Bit Version #########################################
Echo Check this Computer - %COMPUTERNAME% - for 32 or 64 Bit Architecture
If %PROCESSOR_ARCHITECTURE%==x86 (
    REM 32 Bit Windows!
    Echo This is a 32 Bit System, using bin\win32
    Echo Copy Files:
    Copy "%CURPATH%bin\win32\*" "%PROGRAMFILES%\Zabbix\" /Y
) else (
    REM 64 Bit Windows!
    Echo This is a 64 Bit System, using bin\win64
    Copy "%CURPATH%bin\win64\*" "%PROGRAMFILES%\Zabbix\" /Y
)
Echo -------------------------------------------------------------------------
REM Copy UserParameter Files
mkdir "%PROGRAMFILES%\Zabbix\UserParameter"
Echo Copy UserParameter Files ...
Copy "%CURPATH%UserParameter\*" "%PROGRAMFILES%\Zabbix\UserParameter\" /Y
Echo -------------------------------------------------------------------------
REM Copy Tool Files
mkdir "%PROGRAMFILES%\Zabbix\Tools"
Echo Copy Tools ...
Copy "%CURPATH%Tools\*" "%PROGRAMFILES%\Zabbix\Tools\" /Y
Echo -------------------------------------------------------------------------
REM
REM
echo Convert Hostname to uppercase and Domainsuffix to lowercase ...
REM Convert ZABBIXHOSTNAMESUFFIX to Lowercase:
setlocal enabledelayedexpansion
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:a=A!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:b=B!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:c=C!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:d=D!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:e=E!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:f=F!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:g=G!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:h=H!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:i=I!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:j=J!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:k=K!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:l=L!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:m=M!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:n=N!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:o=O!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:p=P!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:q=Q!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:r=R!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:s=S!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:t=T!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:u=U!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:v=V!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:w=W!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:x=X!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:y=Y!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:z=Z!

set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:A=a!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:B=b!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:C=c!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:D=d!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:E=e!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:F=f!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:G=g!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:H=h!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:I=i!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:J=j!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:K=k!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:L=l!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:M=m!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:N=n!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:O=o!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:P=p!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:Q=q!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:R=r!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:S=s!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:T=t!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:U=u!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:V=v!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:W=w!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:X=x!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:Y=y!
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:Z=z!
REM and Spaces to Underline
set ZABBIXHOSTNAMESUFFIX=!ZABBIXHOSTNAMESUFFIX:^ =_!
set ZABBIXHOSTNAME=!ZABBIXHOSTNAME:^ =_!
setlocal disabledelayedexpansion
Echo Hostname is        : %ZABBIXHOSTNAME%
Echo Hostname-suffix is : %ZABBIXHOSTNAMESUFFIX%
REM
REM Create Config-file #######################################################
Echo Creating the File: "%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo Existing File will be Override!!
REM The File!
REM ### Writing Header #######################################################
Echo # This is a config file for the Zabbix agent daemon (Windows) >"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # To get more information about Zabbix, go to http://www.zabbix.com >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # Description of Parameters: >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # Version 2.2.x: https://www.zabbix.com/documentation/2.2/manual/appendix/install/windows_agent >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #                https://www.zabbix.com/documentation/2.2/manual/appendix/config/zabbix_agentd_win >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # Version 2.4.x: https://www.zabbix.com/documentation/2.4/manual/appendix/install/windows_agent >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #                https://www.zabbix.com/documentation/2.4/manual/appendix/config/zabbix_agentd_win >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # Version 3.0.x: https://www.zabbix.com/documentation/3.0/manual/appendix/install/windows_agent >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #                https://www.zabbix.com/documentation/3.0/manual/appendix/config/zabbix_agentd_win >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ####################################################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###   ######   #######   ###  ###  ###  ###  ###   ########  >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###  ########  ########  #### ###  ###  #### ###  #########  >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###  ###  ###  ###  ###  ########  ###  ########  ###        >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###  ###  ###  ###  ###  ########  ###  ########  ###        >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###  ########  #######   ### ####  ###  ### ####  ### #####  >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###  ########  ######    ###  ###  ###  ###  ###  ### #####  >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###  ###  ###  ### ###   ###  ###  ###  ###  ###  ###   ###  >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ###  ###  ###  ###  ###  ###  ###  ###  ###  ###  ###  ###  ###   ###  >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo  #### ## ###   ##   ###  ##   ###   ##   ##   ##   ##   ##   ### ####  >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo   ## #  # #     #   # #   #   # #  ##    #   #    ##    #    ## ## #   >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ####################################################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # THIS FILE WAS CREATED BY AUTOMATED SETUP! SETTINGS MAYBE OVERWRITE AT >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # NEXT UPDATE! >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # The Setupfile is: %CURPATH%%SCRIPTNAME% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ####################################################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM ### Writing Parameter ####################################################
Echo ############ GENERAL PARAMETERS ######################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo LogFile=%SYSTEMDRIVE%\zabbix_agentd.log >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo LogFileSize=5 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #	Specifies debug level ################################################ >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #	0 - no debug >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #	1 - critical information >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #	2 - error information >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #	3 - warnings >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #	4 - for debugging (produces lots of information) >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo DebugLevel=3 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo EnableRemoteCommands=1 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo LogRemoteCommands=1 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo Server=%ZABBIXSERVER% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ListenPort=%ZABBIXHOSTLISTENPORT% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # ListenIP=0.0.0.0 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # StartAgents=3 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
If "%ZABBIXSERVERACTIVE%"=="" (
    Echo ServerActive=%ZABBIXSERVER%:%ZABBIXSERVERPORT% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
) Else (
    Echo ServerActive=%ZABBIXSERVERACTIVE%:%ZABBIXSERVERPORT% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
)
If "%USEDOMAINSUFFIX%" == "YES" (
    Echo Hostname=%ZABBIXHOSTNAME%%ZABBIXHOSTNAMESUFFIX% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
) Else (
    Echo Hostname=%ZABBIXHOSTNAME% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
)
Echo RefreshActiveChecks=120 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # BufferSend=5 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # BufferSize=100 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # MaxLinesPerSecond=100 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo Timeout=30 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"

Echo # Set UnsafeUserParameter to 1 for ###################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # using special chars in Parameters and performance counters ############ >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo UnsafeUserParameters=1 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM ### HostMetadata #########################################################
REM # Check if this Server is a Terminalserver with Citrix XenApp 6.x or 7.x



REM Write HostMetadata if there anyone ***************************************
If "%ZABBIXHOSTMETADATA%" == "" GoTo NOZABBIXMETADATA
REM ## Tests for HostMetadata ########################################################
Echo Try some Test for HostMetadata String for Zabbix Autoregistration
REM ## Test for Citrix XenApp 6.x
Echo Check for Citrix XenApp 6.x
reg query HKLM\SOFTWARE\Citrix\Roles\XenApp\XenAppServerFeature 2>NUL >NUL
If NOT ERRORLEVEL 1 (
    If "%METADATATEST%" == "YES" (
        Set ZABBIXHOSTMETADATA=%ZABBIXHOSTMETADATACITRIX%
        Set METADATATEST=NO
        Echo We have a winner! XenApp 6.x is installed! Skipping all other Test
    )
)
REM ## Test for Citrix XenApp 7.x
Echo Check for Citrix XenApp 7.x
reg query HKLM\SOFTWARE\Citrix\VirtualDesktopAgent 2>NUL >NUL
If NOT ERRORLEVEL 1 (
    If "%METADATATEST%" == "YES" (
        Set ZABBIXHOSTMETADATA=%ZABBIXHOSTMETADATACITRIX%
        Set METADATATEST=NO
        Echo We have a winner! XenApp 7.x is installed! Skipping all other Test
    )
)
REM ## Test for Microsoft SQL Server
Echo Check for Microsoft SQL
REM reg query HKLM\SYSTEM\CurrentControlSet\services | findstr "MSSQL" 2>NUL >NUL
reg query "HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL" 2>NUL >NUL
If NOT ERRORLEVEL 1 (
    If "%METADATATEST%" == "YES" (
        Set ZABBIXHOSTMETADATA=%ZABBIXHOSTMETADATAMSSQL%
        Set METADATATEST=NO
        Echo We have a winner! Microsoft SQL Server is installed! Skipping all other Test
    )
)

REM ## Test for Microsoft Exchange Server
Echo Check for Microsoft Exchange
REM reg query HKLM\SYSTEM\CurrentControlSet\services | findstr "MSExchange" 2>NUL >NUL
If "%ExchangeInstallPath%" NEQ "" (
    If "%METADATATEST%" == "YES" (
        Set ZABBIXHOSTMETADATA=%ZABBIXHOSTMETADATAEXCHANGE%
        REM Set METADATATEST=NO
        Echo We have a winner! Microsoft Exchange Server is installed! Skipping all other Test
    )
)

REM ## Test for Microsoft Exchange Server
Echo Check for Active Directory Domain Controller
reg query HKLM\SYSTEM\CurrentControlSet\services\NTDS | findstr "Parameters" 2>NUL >NUL
If NOT ERRORLEVEL 1 (
    If "%METADATATEST%" == "YES" (
        Set ZABBIXHOSTMETADATA=%ZABBIXHOSTMETADATADC%
        Set METADATATEST=NO
        Echo We have a winner! This Server is an Active Directory Domain Controller! Skipping all other Test
    )
)


REM All Tests are done
Echo Hostmetadata is: %ZABBIXHOSTMETADATA%
Echo # For AutoRegistration ################################################## >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo HostMetadata=%ZABBIXHOSTMETADATA% >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
:NOZABBIXMETADATA
REM
REM
REM ### Writing UserParameter ################################################
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # UserParamter: ######################################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"

REM For Windows Volume Mountpoints without Driveletter but mounted at NTFS-Folder
Echo UserParameter=vfs.fs.znil.windowsmountpoints.discovery,"%PROGRAMFILES%\Zabbix\UserParameter\WindowsMountPoints.exe" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM For AgentAutoUpdate - Check last time of Updates
Echo UserParameter=znil.agentautoupdate[*],"%PROGRAMFILES%\Zabbix\UserParameter\AgentAutoUpdate.exe" $1 >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM For Check Windows Updates
Echo UserParameter=znil.windowsupdates,"%PROGRAMFILES%\Zabbix\UserParameter\windowsupdates.exe" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM For Check Windows License Status (german and englisch Windows Versions)
Echo UserParameter=znil.LicenseStatus,cscript.exe //Nologo %WINDIR%\system32\slmgr.vbs /dli ^| find "License Status:" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo UserParameter=znil.LizenzStatus,cscript.exe //Nologo %WINDIR%\system32\slmgr.vbs /dli ^| find "Lizenzstatus:" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM For more File and Folder Checks
Echo UserParameter=znil.fileandfolder[*],"%PROGRAMFILES%\Zabbix\UserParameter\fileandfolder.exe" "$1" "$2" "$3" "$4" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM Citrix XenDesktop
REM Local Administrators Group monitoring
Echo UserParameter=znil.LocalAdministrators,"%PROGRAMFILES%\Zabbix\UserParameter\LocalAdministrators.exe" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM Task Scheduler Monitoring
Echo UserParameter=znil.TaskSchedulerMonitoring[*],"%PROGRAMFILES%\Zabbix\UserParameter\TaskSchedulerMonitoring.exe" "$1" "$2" "$3" "$4" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
REM Process Monitoring with Commandline
echo UserParameter=znil.ProcessMonitoringPowerShell[*],powershell "@(Get-WmiObject Win32_Process -Filter \"Name = '$1'\" | where {$_.CommandLine -match '$2'}).count" >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"

REM ###########################################################################
REM ###########################################################################
REM ###########################################################################
REM ###########################################################################
REM ### Check Include-File ####################################################
If EXIST "%CURPATH%Include\zabbix_agentd.win.include.txt" (
Copy "%CURPATH%Include\zabbix_agentd.win.include.txt" "%PROGRAMFILES%\Zabbix\zabbix_agentd.win.include.txt" /Y
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # Include additional File with UserParameter: ############################ >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo Include=%PROGRAMFILES%\Zabbix\zabbix_agentd.win.include.txt>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"

) ELSE (
echo No Include File found: %CURPATH%Include\zabbix_agentd.win.include.txt
echo Skip Including File!
)

REM
REM
REM ### Writing Who did this #################################################
Echo. >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ####################################################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # This File was created with Zabbix-Agent-Installer Script>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # 2014 - 2017 by Bernhard Linz -- Bernhard.Linz@datagroup.de>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #                                 Bernhard@znil.net>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # Website:                        http://znil.net>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo # Latest Version at http://znil.net/index.php?title=Zabbix>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #>>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #    ######## ##    ## #### ##             ##    ## ######## ######## >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #         ##  ###   ##  ##  ##             ###   ## ##          ##    >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #        ##   ####  ##  ##  ##             ####  ## ##          ##    >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #       ##    ## ## ##  ##  ##             ## ## ## ######      ##    >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #      ##     ##  ####  ##  ##             ##  #### ##          ##    >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #     ##      ##   ###  ##  ##        ###  ##   ### ##          ##    >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #    ######## ##    ## #### ########  ###  ##    ## ########    ##    >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo #                                                                   >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo ####################################################################### >>"%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%"
Echo Writing File Complete!
Echo -------------------------------------------------------------------------
REM
REM
REM Create Zabbix-Agent-Restart-Script
Echo Create Zabbix-Agent-Restart-Script ...
Echo @Echo off>"%PROGRAMFILES%\Zabbix\zz_Restart-Zabbix-Agent.cmd"
Echo net stop "zabbix agent">>"%PROGRAMFILES%\Zabbix\zz_Restart-Zabbix-Agent.cmd"
Echo net start "zabbix agent">>"%PROGRAMFILES%\Zabbix\zz_Restart-Zabbix-Agent.cmd"
Echo Exit 0>>"%PROGRAMFILES%\Zabbix\zz_Restart-Zabbix-Agent.cmd"
Echo -------------------------------------------------------------------------
REM Create znilTail.exe Script
Echo Create znilTail.exe call with the Zabbix Agent Logfile:
Echo @Echo off>"%PROGRAMFILES%\Zabbix\znilTail-with-zabbix_agentd.log.cmd"
Echo start "" /B "%PROGRAMFILES%\Zabbix\Tools\znilTail.exe" "%SYSTEMDRIVE%\zabbix_agentd.log">>"%PROGRAMFILES%\Zabbix\znilTail-with-zabbix_agentd.log.cmd"
Echo Exit 0>>"%PROGRAMFILES%\Zabbix\znilTail-with-zabbix_agentd.log.cmd"
Echo -------------------------------------------------------------------------
REM
REM Create Firewall Rules
Echo Delete existing Firewall-Rules for Zabbix Agent
Echo Ignore Errors !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
netsh advfirewall firewall delete rule name="Zabbix agentd port %ZABBIXHOSTLISTENPORT% inbound" dir=in
netsh advfirewall firewall delete rule name="Zabbix agentd port %ZABBIXHOSTLISTENPORT% outbound" dir=out
netsh advfirewall firewall delete rule name="Zabbix to Server port %ZABBIXSERVERPORT% inbound" dir=in
netsh advfirewall firewall delete rule name="Zabbix to Server port %ZABBIXSERVERPORT% outbound" dir=out
Echo Create Firewall-Rules for Zabbix Agent
Echo Ignore Errors on Windows XP / 2003 or lower!
REM we would get Errors at Windows XP and maybe at Windows 2003 and lower (no advfirewall context) - but no matter
netsh advfirewall firewall add rule name="Zabbix agentd port %ZABBIXHOSTLISTENPORT% inbound" dir=in action=allow protocol=TCP localport=%ZABBIXHOSTLISTENPORT%
netsh advfirewall firewall add rule name="Zabbix agentd port %ZABBIXHOSTLISTENPORT% outbound" dir=out action=allow protocol=TCP localport=%ZABBIXHOSTLISTENPORT%
netsh advfirewall firewall add rule name="Zabbix to Server port %ZABBIXSERVERPORT% inbound" dir=in action=allow protocol=TCP localport=%ZABBIXSERVERPORT%
netsh advfirewall firewall add rule name="Zabbix to Server port %ZABBIXSERVERPORT% outbound" dir=out action=allow protocol=TCP localport=%ZABBIXSERVERPORT%
if errorlevel 1 (
    Echo There were Errors while adding the Firewall-Rules, ok then we try the Windows Server 2003 and XP way ...
    netsh firewall delete portopening TCP %ZABBIXHOSTLISTENPORT%
    netsh firewall delete portopening TCP %ZABBIXSERVERPORT%
    netsh firewall add portopening TCP %ZABBIXHOSTLISTENPORT% ZabbixAgentPort
    netsh firewall add portopening TCP %ZABBIXSERVERPORT% ZabbixServerPort
)
Echo -------------------------------------------------------------------------
REM Install Zabbix Service and Start Agent
Echo Install Zabbix-Service ...
"%PROGRAMFILES%\Zabbix\zabbix_agentd.exe" -c "%PROGRAMFILES%\Zabbix\%ZABBIXHOSTCONFIGFILE%" --install
Echo Starting the Zabbix Service ...
net start "zabbix agent"
Echo.
If "%ZABBIXAGENTUPDATER%" == "YES" (
  Echo Install ZabbixAgentAutoUpdate Task ...
  If "%UPDATEUSER%" == "SYSTEM" (
    Echo ... Installing Task as SYSTEM User ...
    "%WINDIR%\system32\schtasks.exe" /create /SC MINUTE /MO %UPDATEFREQUENCY% /F /TN ZabbixAgentAutoUpdater /RU SYSTEM /TR "\"%PROGRAMFILES%\Zabbix\UserParameter\AgentAutoUpdate.exe\" \"%UPDATEFILESHARE%\" \"%UPDATEINSTALLER%\""
  ) Else (
    Echo ... Installing Task as user %UPDATEUSER%
    "%WINDIR%\system32\schtasks.exe" /create /SC MINUTE /MO %UPDATEFREQUENCY% /F /TN ZabbixAgentAutoUpdater /RU %UPDATEUSER% /RP %UPDATEPASSWORD% /TR "\"%PROGRAMFILES%\Zabbix\UserParameterAgentAutoUpdate.exe\" \"%UPDATEFILESHARE%\" \"%UPDATEINSTALLER%\""
  )
)
REM Set Zabbix Agent Service to "Automatic (Delayed Start)", will work after next reboot
Echo Set Zabbix Agent Service to "Automatic (Delayed Start)"
reg add "HKLM\SYSTEM\CurrentControlSet\services\Zabbix Agent" /v DelayedAutostart /t REG_DWORD /d 1 /f

REM Write Installation Date and Time to Registry for Zabbix Agent Auto Update to Registry
"%PROGRAMFILES%\Zabbix\UserParameter\AgentAutoUpdate.exe" settime
REM Disable the next Time Update, write only Hash Values to Registry
REM "%PROGRAMFILES%\Zabbix\AgentAutoUpdate.exe" NextTimeOnlyHashUpdate

REM #########################################################################################################
:END
Echo -------------------------------------------------------------------------
Echo ALL ACTION COMPLETED ! Bye Bye!
Echo -------------------------------------------------------------------------
REM remove next REM to read Messages if you run this Script with Doubleclick
REM Pause
REM choice /N /C 123 /T 10 /D 1 /M "Wait 10 Seconds ..."
REM Next Line with Exit is needed for AgentAutoUpdate - CMD Windows will not close without it

Exit 0
