@echo off
setlocal

set "AGENT_MSI=GLPI-Agent-1.15-x64.msi"
set "AGENT_URL=https://dist.lanplm.ru/Utils/GLPI-Agent-1.15-x64.msi"
set "GLPI_SERVER=https://glpi.lanplm.ru"
set "TEMP_DIR=C:\Temp"
set "AGENT_DIR=C:\Program Files\GLPI-Agent"

:: URL сервера уведомлений — заменить на адрес своего VPS
set "NOTIFY_URL=http://notify.lanplm.ru/notify"
openfiles >nul 2>&1
if errorlevel 1 (
    powershell -Command "Start-Process '%~f0' -Verb RunAs"
    exit /b
)

:: Инициализация лога
if not exist "%TEMP_DIR%" mkdir "%TEMP_DIR%"
set "LOG_FILE=%TEMP_DIR%\glpi-install.log"
call :LOG "=== GLPI Agent install started ==="

echo Checking GLPI server...
call :LOG "Checking GLPI server..."
ping -n 1 glpi.lanplm.ru >nul 2>&1
if errorlevel 1 (
    call :LOG "ERROR: Server not reachable."
    echo Server not reachable.
    pause
    exit /b 1
)
call :LOG "Server OK."

echo Downloading MSI...
call :LOG "Downloading %AGENT_URL%"
powershell -Command "Invoke-WebRequest -Uri '%AGENT_URL%' -OutFile '%TEMP_DIR%\%AGENT_MSI%' -UseBasicParsing"
if errorlevel 1 (
    call :LOG "ERROR: Download failed."
    echo Download failed.
    pause
    exit /b 1
)
call :LOG "Download OK."

:: Удаление предыдущей версии если установлена
echo Checking for existing installation...
call :LOG "Checking for existing GLPI Agent installation..."
set "AGENT_GUID="
for /f "tokens=*" %%G in ('powershell -NoProfile -Command "Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall,HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall -ErrorAction SilentlyContinue | Get-ItemProperty | Where-Object { $_.DisplayName -like '*GLPI*Agent*' } | Select-Object -ExpandProperty PSChildName"') do set "AGENT_GUID=%%G"
if defined AGENT_GUID (
    call :LOG "Found existing installation: %AGENT_GUID%. Uninstalling..."
    echo Uninstalling previous version...
    net stop glpi-agent >nul 2>&1
    msiexec /x "%AGENT_GUID%" /quiet /norestart
    call :LOG "Uninstall completed."
) else (
    call :LOG "No existing installation found."
)

echo Installing...
call :LOG "Running msiexec..."
msiexec /i "%TEMP_DIR%\%AGENT_MSI%" /quiet /norestart /l*v "%TEMP_DIR%\glpi-msi.log" SERVER=%GLPI_SERVER% NO_SSL_CHECK=1
if errorlevel 1 (
    call :LOG "ERROR: Installation failed (see %TEMP_DIR%\glpi-msi.log)."
    echo Installation failed. See %TEMP_DIR%\glpi-msi.log
    pause
    exit /b 1
)
call :LOG "Installation OK."

echo Running inventory and sending to server...
set "INVENTORY_FILE=%TEMP_DIR%\inventory.json"
call :LOG "Running glpi-inventory..."
cmd /c ""%AGENT_DIR%\glpi-inventory" --json > "%INVENTORY_FILE%""
call :LOG "glpi-inventory exited."

if not exist "%INVENTORY_FILE%" (
    call :LOG "ERROR: Inventory file not created."
    echo Inventory file not created.
    pause
    exit /b 1
)
set "_FSIZE=0"
for %%F in ("%INVENTORY_FILE%") do set "_FSIZE=%%~zF"
call :LOG "Inventory file size: %_FSIZE% bytes"
if "%_FSIZE%"=="0" (
    call :LOG "ERROR: Inventory file is empty."
    echo Inventory file is empty.
    pause
    exit /b 1
)

echo Sending inventory...
call :LOG "Running glpi-injector..."
cmd /c ""%AGENT_DIR%\glpi-injector" --file "%INVENTORY_FILE%" --url %GLPI_SERVER% --no-ssl-check"
if errorlevel 1 (
    call :LOG "ERROR: glpi-injector failed."
    echo Inventory send failed. See %LOG_FILE%
    pause
    exit /b 1
)
call :LOG "Inventory sent OK."

if exist "%INVENTORY_FILE%" del "%INVENTORY_FILE%"

if exist "%TEMP_DIR%\%AGENT_MSI%" del "%TEMP_DIR%\%AGENT_MSI%"

call :LOG "=== Done ==="
call :NOTIFY "OK"
echo.
echo ========================================
echo   GLPI Agent successfully installed!
echo ========================================
echo.
echo Log: %LOG_FILE%
echo.
pause
endlocal
exit /b 0

:: --- Функция уведомления ---
:NOTIFY
powershell -NoProfile -Command ^
    "$body = ConvertTo-Json @{ timestamp=(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'); computer=$env:COMPUTERNAME; user=$env:USERNAME; status='%~1' };" ^
    "Invoke-WebRequest -Uri '%NOTIFY_URL%' -Method POST -Body $body -ContentType 'application/json' -UseBasicParsing | Out-Null" >nul 2>&1
exit /b

:: --- Функция логирования ---
:LOG
set "_TS="
for /f "tokens=1-2 delims= " %%A in ('powershell -NoProfile -Command "Get-Date -Format 'yyyy-MM-dd HH:mm:ss'"') do set "_TS=%%A %%B"
echo [%_TS%] %~1
echo [%_TS%] %~1 >> "%LOG_FILE%"
exit /b