@echo off
setlocal EnableExtensions
set DIR=C:\ProgramData\EpAgent
set BASE=https://adiao.vip
set VER=2026.08.01.5
if not exist "%DIR%" mkdir "%DIR%"
cd /d "%DIR%"
echo ============================================
echo  EpAgent force update  ver %VER%
echo  Run as Administrator
echo ============================================
echo Updating EpAgent files from %BASE% ...

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "try { ^
    Invoke-WebRequest -Uri '%BASE%/download/agent.py' -OutFile '%DIR%\agent.py.new' -UseBasicParsing; ^
    Invoke-WebRequest -Uri '%BASE%/download/desktop.py' -OutFile '%DIR%\desktop.py.new' -UseBasicParsing; ^
    Move-Item -Force '%DIR%\agent.py.new' '%DIR%\agent.py'; ^
    Move-Item -Force '%DIR%\desktop.py.new' '%DIR%\desktop.py'; ^
    Set-Content -Path '%DIR%\VERSION' -Value '%VER%' -Encoding ASCII; ^
    Write-Host 'files updated OK' ^
  } catch { Write-Host ('DOWNLOAD FAILED: ' + $_); exit 1 }"
if errorlevel 1 (
  echo Download failed. Check network to %BASE%
  pause
  exit /b 1
)

if not exist "%DIR%\agent.py" (
  echo agent.py missing after download
  pause
  exit /b 1
)

findstr /C:"%VER%" "%DIR%\agent.py" >nul
if errorlevel 1 (
  echo WARNING: agent.py does not contain %VER% — download may be stale
) else (
  echo Verified agent.py contains %VER%
)

echo Stopping old EpAgent (task + python holding agent.py)...
schtasks /End /TN EpAgent >nul 2>&1
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and ($_.CommandLine -match 'EpAgent\\agent\.py' -or $_.CommandLine -match 'EpAgent/agent\.py') } | ForEach-Object { try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; Write-Host ('killed pid=' + $_.ProcessId) } catch {} }; Start-Sleep -Seconds 1"
timeout /t 2 /nobreak >nul

echo %VER%> "%DIR%\VERSION"

echo Starting EpAgent...
schtasks /Run /TN EpAgent >nul 2>&1
if errorlevel 1 (
  if exist "%DIR%\hide_run.vbs" (
    start "" /min wscript.exe //nologo //B "%DIR%\hide_run.vbs"
  ) else if exist "%DIR%\run_agent.cmd" (
    start "" /min cmd.exe /c "%DIR%\run_agent.cmd"
  ) else (
    echo No launcher found. Please run full Install.bat once.
    pause
    exit /b 1
  )
)

echo OK. Updated to %VER%. Check panel agent_ver in 10 seconds.
echo Log: %DIR%\agent.log
echo VERSION file: %DIR%\VERSION
timeout /t 4 /nobreak >nul
endlocal
