@echo off

rem Check if running as administrator
net session >nul 2>&1
if %errorlevel% NEQ 0 (
    echo Administrator rights required. Please run the script as an administrator.
    pause
    exit /b 1
)

rem Set folder reference
set "TEAMVIEWER_FOLDER=%~dp0TeamViewer Files"

rem Check if TeamViewer is already installed
reg query "HKLM\SOFTWARE\TeamViewer" >nul 2>&1
if %errorlevel% EQU 0 (
    rem Get the current TeamViewer version
    for /f "tokens=3*" %%a in ('reg query "HKLM\SOFTWARE\TeamViewer" /v Version') do set "CURRENT_VERSION=%%b"

    rem Extract major version from the current version
    for /f "tokens=1 delims=." %%c in ("%CURRENT_VERSION%") do set "CURRENT_MAJOR_VERSION=%%c"

    rem Extract major version from the installed version
    for /f "tokens=1 delims=." %%d in ("%TEAMVIEWER_VERSION%") do set "INSTALLED_MAJOR_VERSION=%%d"

    if "%INSTALLED_MAJOR_VERSION%" geq "%CURRENT_MAJOR_VERSION%" (
        echo TeamViewer %CURRENT_VERSION% is already installed. Closing installer...
        timeout 2 > NUL
        exit /b 0
    )

    if "%INSTALLED_MAJOR_VERSION%" neq "%CURRENT_MAJOR_VERSION%" (
        echo Please uninstall TeamViewer %CURRENT_VERSION% before installing this version. Cannot update the current version.
        pause
        exit /b 1
    )
) else (
    echo Installing TeamViewer... Please wait!
    set "INSTALL_PARAMS=--alias %COMPUTERNAME% --reassign --group ::New"
)

start /wait MSIEXEC.EXE /i "%TEAMVIEWER_FOLDER%\TeamViewer_Host.msi" /qn CUSTOMCONFIGID=64m83mj SETTINGFILE="%TEAMVIEWER_FOLDER%\TeamViewer_Settings.tvopt" APITOKEN=23370927-NF1wbazdxV5oyL36BVvd ASSIGNMENTOPTIONS="--grant-easy-access %INSTALL_PARAMS%"

echo.
echo TeamViewer Installed!



timeout 2 > NUL

