@echo off
setlocal EnableExtensions EnableDelayedExpansion

title TeamViewer Host Reinstall using Browser Download
color 0A

set "TVURL=https://get.teamviewer.com/gmehost"
set "DOWNLOAD_DIR=%USERPROFILE%\Downloads"
set "LOGDIR=C:\Temp"
set "LOGFILE=%LOGDIR%\TeamViewerInstall.log"
set "WAIT_SECONDS=300"
set "CHOICE_TIMEOUT=10"
set "MIN_SIZE=500000"
set "STABLE_REQUIRED=3"
set "UNINSTALL_TIMEOUT=20"

set "INSTALLER="
set "TVEXE="
set "STARTUP_SHORTCUT=%ProgramData%\Microsoft\Windows\Start Menu\Programs\StartUp\TeamViewer.lnk"
set "VBSFILE=%TEMP%\CreateTeamViewerStartup.vbs"

if not exist "%LOGDIR%" mkdir "%LOGDIR%" >nul 2>&1

echo ==================================================
echo   TeamViewer Host Reinstall using Browser Download
echo ==================================================
echo.
echo [%date% %time%] Script started>>"%LOGFILE%"

:: --------------------------------------------------
:: Run as admin
:: --------------------------------------------------
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo Requesting administrator permission...
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /b
)

:: --------------------------------------------------
:: STEP 1 - Stop TeamViewer
:: --------------------------------------------------
echo [1/8] Stopping TeamViewer processes...
echo [%date% %time%] Stopping TeamViewer processes>>"%LOGFILE%"

taskkill /f /im TeamViewer.exe >nul 2>&1
taskkill /f /im TeamViewer_Desktop.exe >nul 2>&1
taskkill /f /im TeamViewer_Service.exe >nul 2>&1
taskkill /f /im tv_x64.exe >nul 2>&1
taskkill /f /im tv_w32.exe >nul 2>&1
taskkill /f /im TeamViewer_Host.exe >nul 2>&1

sc stop TeamViewer >nul 2>&1
sc stop TeamViewer_Service >nul 2>&1
timeout /t 3 /nobreak >nul

:: --------------------------------------------------
:: STEP 2 - Uninstall old TeamViewer
:: --------------------------------------------------
echo [2/8] Uninstalling old TeamViewer Client or Host...
echo [%date% %time%] Uninstalling old TeamViewer>>"%LOGFILE%"

call :RUN_UNINSTALL "C:\Program Files\TeamViewer\uninstall.exe"
call :RUN_UNINSTALL "C:\Program Files (x86)\TeamViewer\uninstall.exe"

taskkill /f /im uninstall.exe >nul 2>&1
taskkill /f /im uninst.exe >nul 2>&1
timeout /t 2 /nobreak >nul

echo Uninstall step completed.
echo [%date% %time%] Uninstall step completed>>"%LOGFILE%"

:: --------------------------------------------------
:: STEP 3 - Clean leftovers
:: --------------------------------------------------
echo [3/8] Removing leftover TeamViewer files...
echo [%date% %time%] Removing leftover TeamViewer files>>"%LOGFILE%"

if exist "%STARTUP_SHORTCUT%" del /f /q "%STARTUP_SHORTCUT%" >nul 2>&1

rmdir /s /q "C:\Program Files\TeamViewer" >nul 2>&1
rmdir /s /q "C:\Program Files (x86)\TeamViewer" >nul 2>&1
rmdir /s /q "%ProgramData%\TeamViewer" >nul 2>&1
rmdir /s /q "%AppData%\TeamViewer" >nul 2>&1
rmdir /s /q "%LocalAppData%\TeamViewer" >nul 2>&1

:: --------------------------------------------------
:: STEP 4 - Open browser for download
:: --------------------------------------------------
echo [4/8] Opening TeamViewer Host download page in browser...
echo [%date% %time%] Opening browser to %TVURL%>>"%LOGFILE%"

start "" "%TVURL%"

echo.
echo Please download the TeamViewer Host installer in your browser.
echo Expected download folder:
echo %DOWNLOAD_DIR%
echo.
echo Expected file name:
echo TeamViewer_Host_Setup.exe
echo.
echo The script will detect the newest TeamViewer Host EXE automatically.
echo.

:: --------------------------------------------------
:: STEP 5 - Wait for downloaded EXE
:: --------------------------------------------------
echo [5/8] Waiting for TeamViewer Host installer download...
echo [%date% %time%] Waiting for browser-downloaded installer>>"%LOGFILE%"

set /a COUNT=0

:WAIT_FOR_INSTALLER
call :FIND_LATEST_INSTALLER

if defined INSTALLER goto FILE_FOUND

set /a COUNT+=1
<nul set /p =.
timeout /t 1 /nobreak >nul

if !COUNT! geq %WAIT_SECONDS% goto TIMEOUT
goto WAIT_FOR_INSTALLER

:FILE_FOUND
echo.
echo Found installer:
echo %INSTALLER%
echo [%date% %time%] Found installer: %INSTALLER%>>"%LOGFILE%"

set /a STABLECOUNT=0
set "LASTSIZE=0"
set "CURSIZE=0"

:CHECK_STABLE
if not exist "%INSTALLER%" (
    echo Installer disappeared. Waiting again...
    set "INSTALLER="
    goto WAIT_FOR_INSTALLER
)

for %%I in ("%INSTALLER%") do set "CURSIZE=%%~zI"
if not defined CURSIZE set "CURSIZE=0"

echo Current size: !CURSIZE! bytes

if !CURSIZE! lss %MIN_SIZE% (
    echo File still looks too small. Probably still downloading.
    echo [%date% %time%] File too small: !CURSIZE! bytes>>"%LOGFILE%"
    goto ASK_WAIT_OR_PROCEED
)

if "!CURSIZE!"=="!LASTSIZE!" (
    set /a STABLECOUNT+=1
) else (
    set /a STABLECOUNT=0
)

set "LASTSIZE=!CURSIZE!"

if !STABLECOUNT! geq %STABLE_REQUIRED% (
    echo Download appears complete.
    echo [%date% %time%] Download stabilized at !CURSIZE! bytes>>"%LOGFILE%"
    goto INSTALL_NOW
)

echo Download still changing...
goto ASK_WAIT_OR_PROCEED

:ASK_WAIT_OR_PROCEED
echo.
echo Press P to proceed now, or W to wait more.
echo Auto-selecting W after %CHOICE_TIMEOUT% seconds if no key is pressed...
choice /c PW /n /t %CHOICE_TIMEOUT% /d W /m "Select [P/W]: "

if errorlevel 2 goto WAIT_MORE
if errorlevel 1 goto INSTALL_NOW

:WAIT_MORE
timeout /t 2 /nobreak >nul
goto CHECK_STABLE

:: --------------------------------------------------
:: STEP 6 - Install
:: --------------------------------------------------
:INSTALL_NOW
echo [6/8] Installing TeamViewer Host...
echo [%date% %time%] Starting installer: %INSTALLER%>>"%LOGFILE%"

if not exist "%INSTALLER%" (
    echo ERROR: Installer file not found.
    echo [%date% %time%] ERROR: Installer file missing before install>>"%LOGFILE%"
    pause
    goto END_ERROR
)

for %%I in ("%INSTALLER%") do set "CURSIZE=%%~zI"
if !CURSIZE! lss %MIN_SIZE% (
    echo ERROR: Installer file still too small.
    echo Size: !CURSIZE! bytes
    echo [%date% %time%] ERROR: Installer file too small before install>>"%LOGFILE%"
    pause
    goto END_ERROR
)

start /wait "" "%INSTALLER%"
set "EXITCODE=%ERRORLEVEL%"

echo Installer exit code: %EXITCODE%
echo [%date% %time%] Installer exit code: %EXITCODE%>>"%LOGFILE%"

timeout /t 5 /nobreak >nul

:: --------------------------------------------------
:: STEP 7 - Find TeamViewer and enable startup
:: --------------------------------------------------
echo [7/8] Enabling TeamViewer startup...
echo [%date% %time%] Enabling TeamViewer startup>>"%LOGFILE%"

if exist "C:\Program Files\TeamViewer\TeamViewer.exe" set "TVEXE=C:\Program Files\TeamViewer\TeamViewer.exe"
if not defined TVEXE if exist "C:\Program Files (x86)\TeamViewer\TeamViewer.exe" set "TVEXE=C:\Program Files (x86)\TeamViewer\TeamViewer.exe"

if not defined TVEXE (
    echo ERROR: TeamViewer.exe not found after installation.
    echo [%date% %time%] ERROR: TeamViewer.exe not found after install>>"%LOGFILE%"
    pause
    goto END_ERROR
)

(
    echo Set oWS = WScript.CreateObject("WScript.Shell"^)
    echo sLinkFile = "%STARTUP_SHORTCUT%"
    echo Set oLink = oWS.CreateShortcut(sLinkFile^)
    echo oLink.TargetPath = "%TVEXE%"
    echo oLink.WorkingDirectory = "C:\"
    echo oLink.WindowStyle = 1
    echo oLink.Description = "Start TeamViewer with Windows"
    echo oLink.Save
) > "%VBSFILE%"

cscript //nologo "%VBSFILE%" >nul 2>&1
del /f /q "%VBSFILE%" >nul 2>&1

:: --------------------------------------------------
:: STEP 8 - Launch TeamViewer
:: --------------------------------------------------
echo [8/8] Opening TeamViewer now...
echo [%date% %time%] Launching TeamViewer>>"%LOGFILE%"

start "" "%TVEXE%"

echo.
echo ==================================================
echo SUCCESS - TeamViewer Host reinstall completed
echo ==================================================
echo Installer: %INSTALLER%
echo TeamViewer: %TVEXE%
echo Log file: %LOGFILE%
echo.

:: --------------------------------------------------
:: FINAL POPUP AFTER CMD CLOSES
:: --------------------------------------------------
start "" powershell -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -Command ^
"Start-Sleep -Seconds 1; ^
 Add-Type -AssemblyName System.Windows.Forms; ^
 Add-Type -AssemblyName System.Drawing; ^
 $form = New-Object System.Windows.Forms.Form; ^
 $form.Text = 'GME TeamViewer'; ^
 $form.Size = New-Object System.Drawing.Size(520,220); ^
 $form.StartPosition = 'CenterScreen'; ^
 $form.Topmost = $true; ^
 $label1 = New-Object System.Windows.Forms.Label; ^
 $label1.Text = 'This PC has been successfully added to GME TeamViewer'; ^
 $label1.AutoSize = $true; ^
 $label1.Font = New-Object System.Drawing.Font('Segoe UI',11,[System.Drawing.FontStyle]::Regular); ^
 $label1.Location = New-Object System.Drawing.Point(30,30); ^
 $label2 = New-Object System.Windows.Forms.Label; ^
 $label2.Text = 'Hostname: %COMPUTERNAME%'; ^
 $label2.AutoSize = $true; ^
 $label2.ForeColor = [System.Drawing.Color]::Red; ^
 $label2.Font = New-Object System.Drawing.Font('Segoe UI',16,[System.Drawing.FontStyle]::Bold); ^
 $label2.Location = New-Object System.Drawing.Point(30,80); ^
 $button = New-Object System.Windows.Forms.Button; ^
 $button.Text = 'OK'; ^
 $button.Width = 90; ^
 $button.Height = 32; ^
 $button.Location = New-Object System.Drawing.Point(200,130); ^
 $button.Add_Click({ $form.Close() }); ^
 $form.Controls.Add($label1); ^
 $form.Controls.Add($label2); ^
 $form.Controls.Add($button); ^
 [void]$form.ShowDialog();"

goto END_OK

:TIMEOUT
echo.
echo ERROR: Timed out waiting for TeamViewer Host download.
echo Please check whether the browser saved the file in:
echo %DOWNLOAD_DIR%
echo [%date% %time%] ERROR: Timed out waiting for installer>>"%LOGFILE%"
pause
goto END_ERROR

:RUN_UNINSTALL
set "UNINSTALLER=%~1"
if not exist "%UNINSTALLER%" exit /b 0

echo Found uninstall file:
echo %UNINSTALLER%
echo [%date% %time%] Found uninstall file: %UNINSTALLER%>>"%LOGFILE%"

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
"$p = Start-Process -FilePath '%UNINSTALLER%' -ArgumentList '/S' -PassThru; ^
 try { Wait-Process -Id $p.Id -Timeout %UNINSTALL_TIMEOUT% -ErrorAction Stop } ^
 catch { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue }"

exit /b 0

:FIND_LATEST_INSTALLER
set "INSTALLER="
set "LATESTFILE="
set "LATESTTIME="

for %%F in ("%DOWNLOAD_DIR%\TeamViewer_Host_Setup*.exe") do (
    if exist "%%~fF" (
        if not defined LATESTTIME (
            set "LATESTTIME=%%~tF"
            set "LATESTFILE=%%~fF"
        ) else (
            if "%%~tF" GTR "!LATESTTIME!" (
                set "LATESTTIME=%%~tF"
                set "LATESTFILE=%%~fF"
            )
        )
    )
)

if defined LATESTFILE set "INSTALLER=%LATESTFILE%"
exit /b

:END_OK
endlocal
exit /b 0

:END_ERROR
endlocal
exit /b 1