@echo off
REM Batch file to start open test agent 

setlocal enableextensions enabledelayedexpansion

for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set ESC=%%b
)

cd /d %~dp0

REM read configuration from agent.conf
for /f "delims== tokens=1,2" %%G in (agent.conf) do set %%G=%%H

if "%PORT%" == "" (
	SET /p "PORT=Specify an HTTP port to run ALM Test Execution Agent (or default 8080):"

	SET CONFIGURATION_CHANGED=Y
)

if "%PORT%" == "" (
	SET PORT=8080
)
	

if "%ALM_SERVER_URL%" == "" (
	set /p ALM_SERVER_URL=Enter the ALM server you're going to connect to:
	SET CONFIGURATION_CHANGED=Y
)

if "%APIKEY_CLIENT%" == "" (
	SET /p APIKEY_CLIENT=Enter an ApiKey client for Test Execution Agent:
	SET CONFIGURATION_CHANGED=Y
)

if "%APIKEY_SECRET%" == "" (
    set /p"APIKEY_SECRET=ApiKey secret:"
    SET CONFIGURATION_CHANGED=Y
)


if "%TOKEN%" == "" (
	SET /p TOKEN=Enter a Host Identifier for Test Execution Agent:
	SET CONFIGURATION_CHANGED=Y
)

if "%IS_SHARED%" == "" (
    <nul set /p"=!BS!!CR!Would you like to share this Test Execution Agent?"
	set /p"IS_SHARED=(Y/N)"
	SET CONFIGURATION_CHANGED=Y
)

REM read configuration from agent.conf
for /f "delims== tokens=1,2" %%G in (agent.ini) do set %%G=%%H
:JAVA_FOLDER
if "%JAVA_BIN%" == "" (
	
	echo =======================================================
	echo %ESC%[31mNOTE: Because Test Execution Agent will talk with ALM OTA platform via COM technology,%ESC%[0m
	echo %ESC%[31mso it can only work with 64 bit JDK/JRE 17%ESC%[0m
	echo ======================================================="
	set /P "JAVA_BIN=Specify bin folder of 64 bit JDK/JRE 17:(which contains java.exe)"

	SET CONFIGURATION_CHANGED=Y
)

if not exist "%JAVA_BIN%\java.exe" (
	echo "Cannot find java.exe in %JAVA_BIN%, make sure the path is correct."
	SET JAVA_BIN=
	goto JAVA_FOLDER
)

REM Save this only if the configuration is changed
if "%CONFIGURATION_CHANGED%" == "Y" (
	echo ALM_SERVER_URL=%ALM_SERVER_URL%>> agent.conf
	echo APIKEY_CLIENT=%APIKEY_CLIENT%>> agent.conf
	echo APIKEY_SECRET=%APIKEY_SECRET%>> agent.conf
	echo "JAVA_BIN=%JAVA_BIN%">> agent.ini
	echo PORT=%PORT%>> agent.conf
	echo TOKEN=%TOKEN%>> agent.conf
	echo IS_SHARED=%IS_SHARED%>>agent.conf
)

SET CONFIGURATION_CHANGED=N
SET TOKEN=""
SET IS_SHARED=""
SET ALM_SERVER_URL=""
SET APIKEY_CLIENT=""
SET APIKEY_SECRET=""
REM TODO: we may need to ask end user to input 32 bit java path
call "%JAVA_BIN%\java.exe" -jar test-execution-agent.jar "--server.port=%PORT%"
SET JAVA_BIN=""
SET PORT=""

pause "Press any key to quit!"
