@echo off
rem The exit codes return by this script.
set SUCCESS=0
set SERVICE_ALREADY_STARTED=30
set SERVICE_NOT_INSTALLED=35
set SERVICE_NOT_STOPPED=40
set NONSPECIFIC_START_FAILURE=45
set GET_STATUS_FAILURE=50

rem Get SFN path to install directory.
rem A bug in some versions of Windows makes %~dsp0 append the filename, so use this workaround.
rem Note: correct to append .. instead of \ since %~dsp0 ends with \
for %%i in (%~sf0) do set INSTALL_DIR=%%~dspi..

set SCRIPT_DIR=%INSTALL_DIR%\bin
set MULE_APP=apia

rem Check if IA service is installed,
echo Checking that Integration Agent service (%MULE_APP%) is stopped...
sc query %MULE_APP% | find "does not exist" >NUL

rem If the search succeeded, then the service is not installed.
IF %ERRORLEVEL% EQU 0 GOTO SERVICE_NOT_INSTALLED

rem Get the IA service's current state.
FOR /F "tokens=3" %%G IN ('sc query %MULE_APP% ^| find "STATE"') DO SET SERVICE_STATE=%%G

rem Nothing to do if the service is already started.
IF %SERVICE_STATE% EQU 4 GOTO SERVICE_ALREADY_STARTED

rem Only continue if the service is stopped.
IF %SERVICE_STATE% NEQ 1 GOTO SERVICE_NOT_STOPPED

rem Start the IA service.
echo Starting Integration Agent service (%MULE_APP%)...
net start %MULE_APP%

rem Notify of failure to start service.
IF %ERRORLEVEL% NEQ 0 GOTO START_FAILURE

rem Service was started, so issue get-status command.
echo Getting the current status...
CALL %SCRIPT_DIR%\iadmin.bat get-status

rem Notify of failure of get-status.
IF %ERRORLEVEL% NEQ 0 GOTO GET_STATUS_FAILURE

echo Successfully started Integration Agent service (%MULE_APP%).
EXIT /B %SUCCESS%

rem *
rem * Error handlers
rem *

:SERVICE_NOT_INSTALLED
echo The Integration Agent service (%MULE_APP%) is not installed.
EXIT /B %SERVICE_NOT_INSTALLED%

:SERVICE_ALREADY_STARTED
echo The Integration Agent service (%MULE_APP%) is already running.
EXIT /B %SERVICE_ALREADY_STARTED%

:SERVICE_NOT_STOPPED
echo The Integration Agent service (%MULE_APP%) can only be started if it is currently stopped.
EXIT /B %SERVICE_NOT_STOPPED%

:START_FAILURE
rem Default service code to 0 so we can detect if parse loop does not run (i.e., service code not found), or is 0 (i.e., service never attempted to start).
set SERVICE_CODE=0

rem Parse the IA service's exit code and return it as the script exit code.
FOR /F "tokens=3" %%G IN ('sc query %MULE_APP% ^| find "SERVICE_EXIT_CODE"') DO SET SERVICE_CODE=%%G

rem If there is no specific service code then indicate this.
IF %SERVICE_CODE% EQU 0 set SERVICE_CODE=%NONSPECIFIC_START_FAILURE%

echo Unable to start Integration Agent service (%MULE_APP%) due to error code %SERVICE_CODE%
echo Consult the script output, system event log, or Integration Agent logs for details.
EXIT /B  %SERVICE_CODE%

:GET_STATUS_FAILURE
echo Successfully started Integration Agent service (%MULE_APP%),
echo but failed to issue "get-status" command via IA Admin CLI.
echo Consult the IA Admin CLI's log file for details.
EXIT /B %GET_STATUS_FAILURE%

