:: agent-svr.bat
:: Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
::
:: Contact:
:: DongHee Yang <donghee.yang@samsung.com>
:: Sungmin Kim <sm.art.kim@samsung.com>
:: Jiil Hyoun <jiil.hyoun@samsung.com>
:: Jonghwan Park <iwin100.park@samsung.com>
:: Kitae Kim <kt920.kim@samsung.com>
::
:: Licensed under the Apache License, Version 2.0 (the "License");
:: you may not use this file except in compliance with the License.
:: You may obtain a copy of the License at
::
:: http://www.apache.org/licenses/LICENSE-2.0
::
:: Unless required by applicable law or agreed to in writing, software
:: distributed under the License is distributed on an "AS IS" BASIS,
:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
:: See the License for the specific language governing permissions and
:: limitations under the License.
::
:: Contributors:
:: - S-Core Co., Ltd

@echo off
setlocal
set "subcommand="
set "id="
set "port="
set BASEDIR=%~dp0
set AGENTAPP=""

if exist %BASEDIR%/agent.js (
    set AGENTAPP=%BASEDIR%/agent.js
)
if exist %BASEDIR%/../plugins/dibs.server.agent/bin/agent.js (
    set AGENTAPP=%BASEDIR%/../plugins/dibs.server.agent/bin/agent.js
)
if %AGENTAPP% EQU "" (
    echo Can not find agent server module
    GOTO DONE
)

reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall /s > %TMP%\regresult.txt
find /C "Node.js" %TMP%\regresult.txt > %TMP%\result.txt
FOR /f "tokens=3" %%p in (%TMP%\result.txt) do set result=%%p

if "%result%" == "0" (
    echo Can not find node.
    GOTO DONE
)
Del %TMP%\result.txt
Del %TMP%\regresult.txt

:PARSE
set "Param=%~1"
if not defined Param goto EXEC
if "%Param%"=="start" set "subcommand=start" & goto Next1
if "%Param%"=="stop" set "subcommand=stop" & goto Next1
if "%Param%"=="-i" set "id=%2" & goto Next2
if "%Param%"=="-p" set "port=%2" & goto Next2
goto ERROR

:Next1
shift
goto PARSE

:Next2
shift & shift
goto PARSE

:EXEC
if "%id%"=="" goto HELP
if defined subcommand if "%subcommand%"=="start" if defined port goto START_SERVER1
if defined subcommand if "%subcommand%"=="start" goto START_SERVER2
if defined subcommand if "%subcommand%"=="stop" goto STOP_SERVER
goto HELP

:START_SERVER1
start node --stack-size=1024 %AGENTAPP% start -i %id% -p %port%
goto DONE

:START_SERVER2
start node --stack-size=1024 %AGENTAPP% start -i %id%
goto DONE

:STOP_SERVER
call node %AGENTAPP% stop -i %id%
goto DONE

:ERROR
echo Invalid Parameter: %1 %2
goto HELP

:HELP
echo Usage "agent-svr.bat {start|stop} -i <serverId> -p <port>"
goto DONE

:DONE
endlocal
