@echo off
rem # ------------------------------------------------------------
rem # Company: Software- und Organisations-Service GmbH
rem # Author : Oliver Haufe <oliver.haufe@sos-berlin.com>
rem # ------------------------------------------------------------

SETLOCAL
set JS7_CONTROLLER_ID=%~1
set JS7_SERVICE_NAME_SUFFIX=%~2
set JS7_CONTROLLER_LOG_DIR=%~3
set JS7_CONTROLLER_HOME=%~4
set /a JS7_CONTROLLER_SERVICE_IS_RUNNING=0
set /a JS7_CONTROLLER_SERVICE_EXIST=1

if not defined JS7_CONTROLLER_ID (
  echo Please enter the JS7 Controller ID
  goto usage
)

goto uninstall

:usage
echo Usage: %~nx0 "id" "[data-dir]" "[log-dir]" "[home-dir]"
call :more_info
echo.
pause
exit /b 0

:more_info
echo see also https://kb.sos-berlin.com/x/kQiX for more information.
goto final

:normalize_home
set JS7_CONTROLLER_HOME=%~dp1
set JS7_CONTROLLER_HOME=%JS7_CONTROLLER_HOME:~0,-1%
goto final

:clear
if exist "%SERVICE_MANAGER%" del "%SERVICE_MANAGER%"
if exist "%SERVICE_INSTALL%" del "%SERVICE_INSTALL%"
goto final

:service_exist
sc.exe query %SERVICE_NAME% > nul
if %ERRORLEVEL% EQU 1060 set /a JS7_CONTROLLER_SERVICE_EXIST=0
goto final

:service_is_running
for /F "usebackq tokens=3 delims=: " %%i in (`sc.exe query %SERVICE_NAME% ^| findstr /I "STATE"`) do (
  if /I x%%i==xRUNNING set /a JS7_CONTROLLER_SERVICE_IS_RUNNING=1
)
goto final

:uninstall
if not defined JS7_CONTROLLER_HOME set JS7_CONTROLLER_HOME=%~dp0..
call :normalize_home "%JS7_CONTROLLER_HOME%\dummy"
if not defined JS7_CONTROLLER_LOG_DIR set JS7_CONTROLLER_LOG_DIR=%JS7_CONTROLLER_HOME%\var\logs
if not exist "%JS7_CONTROLLER_LOG_DIR%" set JS7_CONTROLLER_LOG_DIR=%JS7_CONTROLLER_HOME%\logs
if not exist "%JS7_CONTROLLER_LOG_DIR%" set JS7_CONTROLLER_LOG_DIR=%TEMP%
set SERVICE_NAME=js7_controller_%JS7_CONTROLLER_ID%
if defined JS7_SERVICE_NAME_SUFFIX set SERVICE_NAME=%SERVICE_NAME%-%JS7_SERVICE_NAME_SUFFIX%
set PROCESSOR_ARCH=amd64
if x%PROCESSOR_ARCHITECTURE:64=%==x%PROCESSOR_ARCHITECTURE% set PROCESSOR_ARCH=x86
set SERVICE_INSTALL_TEMPLATE=%JS7_CONTROLLER_HOME%\service\%PROCESSOR_ARCH%\prunsrv.exe
set SERVICE_INSTALL=%JS7_CONTROLLER_HOME%\service\%SERVICE_NAME%.exe
set SERVICE_MANAGER=%JS7_CONTROLLER_HOME%\service\%SERVICE_NAME%w.exe

call :service_exist
if %JS7_CONTROLLER_SERVICE_EXIST% equ 0 (
  echo "%SERVICE_NAME%" service doesn't exist.
  exit /B 0
) 
if not exist "%SERVICE_INSTALL%" (
  echo the daemon "%SERVICE_INSTALL%" for the "%SERVICE_NAME%" service doesn't exist.
  echo ...try to copy "%SERVICE_INSTALL_TEMPLATE%" to "%SERVICE_INSTALL%"
  copy /Y "%SERVICE_INSTALL_TEMPLATE%" "%SERVICE_INSTALL%"
  if ERRORLEVEL 1 exit /B %ERRORLEVEL%
)
call :service_is_running
if %JS7_CONTROLLER_SERVICE_IS_RUNNING% equ 1 "%SERVICE_INSTALL%" //SS/%SERVICE_NAME% 
"%SERVICE_INSTALL%" //DS/%SERVICE_NAME% 
 
if not errorlevel 1 (
  echo "%SERVICE_NAME%" service has been deleted
  call :clear
  goto final
)
echo Failed to delete "%SERVICE_NAME%" service. Refer to log in %JS7_CONTROLLER_LOG_DIR%

ENDLOCAL
:final