@echo off
setlocal EnableExtensions EnableDelayedExpansion
title DeoDap Watcher - Update and Repair

REM ===========================================================================
REM  ONE FILE. Installs 1.4.19 and repairs the machine in the same pass.
REM
REM  No enrollment token, and deliberately so: an enrollment token is bound to a
REM  single employeeId, so reusing one across 34 machines would reassign all 34
REM  to the same person and destroy attribution. 1.4.19 does not need one — it
REM  resolves consent from the HEARTBEAT, which authenticates by the durable
REM  device token, so a machine whose sign-in has lapsed repairs itself within
REM  one ping with nobody at the keyboard.
REM
REM  The installer's own customInstall step reinstalls DeoDapWatcherService and
REM  the DeoDapWatcherAgent task, so this IS the repair. It runs that step
REM  DETACHED and never reports failure, which is why this script verifies
REM  afterwards instead of trusting the exit code.
REM
REM  Upgrading keeps %APPDATA%\DeoDap Watcher, so the device token, the device's
REM  identity in the console and its history all survive. Nothing is uninstalled
REM  and nothing is deleted.
REM ===========================================================================

set "VER=1.4.19"
set "URL=https://apps.deodap.info/deodap/apps/DeoDap-Watcher-%VER%-win-x64.exe"
set "DL=%TEMP%\DeoDap-Watcher-%VER%-win-x64.exe"

net session >nul 2>&1
if %errorlevel% neq 0 (
  echo Asking for administrator permission...
  powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs" >nul 2>&1
  exit /b
)

echo(
echo  ================================================
echo    DeoDap Watcher - update to %VER% and repair
echo  ================================================
echo(
echo  [1/4] Downloading (about 90 MB, please wait)...

del /f /q "%DL%" >nul 2>&1

REM Ask what the server says BEFORE downloading, so the failure message can name
REM the real cause. "Check your internet" is actively misleading when the true
REM answer is that this version was never published — it sends whoever is at the
REM machine chasing a network that is working fine.
set "CODE=000"
curl.exe -sIL --max-time 30 -o nul -w "%%{http_code}" "%URL%" > "%TEMP%\ddw_code.txt" 2>nul
if exist "%TEMP%\ddw_code.txt" set /p CODE=<"%TEMP%\ddw_code.txt"
del /f /q "%TEMP%\ddw_code.txt" >nul 2>&1

if not "!CODE!"=="200" (
  echo(
  if "!CODE!"=="404" (
    echo  [X] Version %VER% is not on the download server yet.
    echo      Nothing is wrong with this PC. Tell IT: "1.4.19 not published".
  ) else if "!CODE!"=="000" (
    echo  [X] Could not reach apps.deodap.info at all.
    echo      Check this PC's internet connection, then run this again.
  ) else (
    echo  [X] The download server answered HTTP !CODE!.
    echo      Tell IT that number - it says what went wrong.
  )
  echo(
  pause
  exit /b 2
)

curl.exe -L --fail --silent --show-error -o "%DL%" "%URL%"
if not exist "%DL%" (
  echo        curl failed, trying PowerShell...
  powershell -NoProfile -Command "try{Invoke-WebRequest -Uri '%URL%' -OutFile '%DL%' -UseBasicParsing}catch{exit 1}"
)
if not exist "%DL%" (
  echo(
  echo  [X] The download did not complete. Run this again.
  echo(
  pause
  exit /b 2
)

REM A truncated download installs "successfully" and leaves a broken app, so
REM refuse anything obviously too small rather than trusting that it arrived.
for %%A in ("%DL%") do set "SZ=%%~zA"
if !SZ! LSS 50000000 (
  echo(
  echo  [X] The download is incomplete (!SZ! bytes^). Try again.
  echo(
  del /f /q "%DL%" >nul 2>&1
  pause
  exit /b 2
)
echo        downloaded (!SZ! bytes^)

echo  [2/4] Closing the tracker if it is running...
taskkill /F /IM "DeoDap Watcher.exe" >nul 2>&1
timeout /t 2 /nobreak >nul

echo  [3/4] Installing %VER% (this also rebuilds the background service)...
"%DL%" /S
REM /S returns immediately on the NSIS assisted installer, so wait for the new
REM binary to actually land rather than racing ahead to the check.
set "APP=%ProgramFiles%\DeoDap Watcher\DeoDap Watcher.exe"
if not exist "%APP%" set "APP=%ProgramFiles(x86)%\DeoDap Watcher\DeoDap Watcher.exe"
for /L %%i in (1,1,60) do (
  timeout /t 3 /nobreak >nul
  sc query DeoDapWatcherService >nul 2>&1 && goto :installed
)
:installed

echo  [4/4] Checking the machine can now keep itself running...
sc config DeoDapWatcherService start= auto >nul 2>&1
sc start  DeoDapWatcherService          >nul 2>&1

set "OK="
for /L %%i in (1,1,15) do (
  if not defined OK (
    timeout /t 2 /nobreak >nul
    REM Let the SERVICE start the tracker. Starting it ourselves would prove
    REM nothing about whether this machine recovers on its own tomorrow.
    tasklist /FI "IMAGENAME eq DeoDap Watcher.exe" 2>nul | find /I "DeoDap Watcher.exe" >nul && set "OK=1"
  )
)

del /f /q "%DL%" >nul 2>&1
echo(
if defined OK (
  echo  ================================================
  echo    [OK]  Done. Version %VER% is installed and
  echo          tracking is running again. It will now
  echo          restart itself automatically.
  echo  ================================================
) else (
  sc query DeoDapWatcherService >nul 2>&1
  if errorlevel 1 (
    echo  ================================================
    echo    [X]  The background service did not install.
    echo         Tell IT: "service missing after %VER%".
    echo  ================================================
  ) else (
    echo  ================================================
    echo    [!]  Service is there, but the tracker did not
    echo         start within 30 seconds.
    echo         Please RESTART the computer once.
    echo  ================================================
  )
)
echo(
pause
