@echo off
setlocal

set "SERVER=https://2f.aiwearlab.com"
set "AGENT_EXE=%~dp0agent\remote-devops-agent-win7.exe"
if not exist "%AGENT_EXE%" set "AGENT_EXE=%~dp0remote-devops-agent-win7.exe"
set "AGENT_PYTHON=%~dp0agent\python.exe"
set "AGENT_PROJECT=%~dp0agent"
set "INSTALL_PS1=%~dp0install-agent-task.ps1"

if exist "%AGENT_EXE%" (
  set "AGENT_MODE=exe"
) else if exist "%AGENT_PYTHON%" (
  set "AGENT_MODE=python"
) else (
  echo Agent executable was not found in agent\ or next to this script.
  echo Expected either agent\remote-devops-agent-win7.exe or agent\python.exe.
  pause
  exit /b 1
)

if not exist "%INSTALL_PS1%" (
  echo install-agent-task.ps1 was not found next to this script.
  pause
  exit /b 1
)

echo RemoteDevops agent installer
echo Server: %SERVER%
echo.
echo A 4-digit pairing code will appear.
echo Send that code to the administrator and keep this window open.
echo.

if "%AGENT_MODE%"=="python" (
  "%AGENT_PYTHON%" -m remote_admin.agent.windows_agent --server "%SERVER%" --name "%COMPUTERNAME%" --pair-only
) else (
  "%AGENT_EXE%" --server "%SERVER%" --name "%COMPUTERNAME%" --pair-only
)
set "EXIT_CODE=%ERRORLEVEL%"
if not "%EXIT_CODE%"=="0" (
  echo Pairing failed with exit code %EXIT_CODE%.
  pause
  exit /b %EXIT_CODE%
)

if "%AGENT_MODE%"=="python" (
  powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%INSTALL_PS1%" -Server "%SERVER%" -Name "%COMPUTERNAME%" -Python "%AGENT_PYTHON%" -ProjectRoot "%AGENT_PROJECT%" -UseExistingConfig
) else (
  powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%INSTALL_PS1%" -Server "%SERVER%" -Name "%COMPUTERNAME%" -AgentExe "%AGENT_EXE%" -UseExistingConfig
)
set "EXIT_CODE=%ERRORLEVEL%"
echo.
if not "%EXIT_CODE%"=="0" (
  echo Install failed with exit code %EXIT_CODE%.
  echo Check: %LOCALAPPDATA%\RemoteDevops\agent-run.log
  pause
  exit /b %EXIT_CODE%
)

echo Install finished.
echo Log: %LOCALAPPDATA%\RemoteDevops\agent-run.log
pause
