@echo off

rem ###############################################################
rem # Copyright (c) Virtimo AG, Germany.
rem # https://www.virtimo.de
rem # All rights reserved.
rem #
rem # Script to stop Karaf and OpenSearch
rem ###############################################################

set CURRENT_DIR=%CD%
for %%i in ("%~dp0..") do set "BPC_DIR=%%~fi"

set KARAF_STOP="%BPC_DIR%\karaf\bin\stop.bat"
set KARAF_STATUS="%BPC_DIR%\karaf\bin\status.bat"
set OPENSEARCH_PID="%BPC_DIR%\opensearch\bin\opensearch.pid"

:CheckKarafRootInstance
    set ROOT_INSTANCE_RUNNING=false
    if exist "%BPC_DIR%\karaf\instances\instance.properties" (
        for /f "delims=" %%x in ( 'findstr "item.0.pid" "%BPC_DIR%\karaf\instances\instance.properties" ' ) do @set pid=%%x
    )
    set ROOT_INSTANCE_PID=%pid:~13%
    SET CHECK_RUNNING_CONDITION=true
    if "%ROOT_INSTANCE_PID%" == "~13" SET CHECK_RUNNING_CONDITION=false
        if "%ROOT_INSTANCE_PID%" == "0" SET CHECK_RUNNING_CONDITION=false
        if "%CHECK_RUNNING_CONDITION%" == "true" (
            tasklist /FI "PID eq %ROOT_INSTANCE_PID%" 2>NUL | find /I /N "java.exe" > NUL
            if not errorlevel 1 set ROOT_INSTANCE_RUNNING=true
        )

rem ###############################
rem # Switch to the BPC base folder
rem ###############################

cd %BPC_DIR%

rem ############
rem # Stop Karaf
rem ############

SET IS_RUNNABLE=false
if "%ROOT_INSTANCE_RUNNING%" == "false" SET IS_RUNNABLE=true
if "%IS_RUNNABLE%" == "true" (
    echo Karaf not running
) else (
    echo Stopping Karaf ...
    call %KARAF_STOP%>NUL
    echo Karaf stopped
)

rem #################
rem # Stop OpenSearch
rem #################

if not exist %OPENSEARCH_PID% goto notExists
:fileExists
SET /P PID_VALUE= < %OPENSEARCH_PID%
tasklist | findstr /r "%PID_VALUE%">NUL
if %ERRORLEVEL% == 0 (
    echo Stopping OpenSearch ...
    taskkill /pid %PID_VALUE% /f>NUL
    echo OpenSearch stopped
    goto end
)
:notExists
echo OpenSearch not running

:end

cd %CURRENT_DIR%
