@echo off
SETLOCAL
:: start.bat logPath dataPath port
set logPath=%~f1
set dataPath=%~f2
set port=%3
set historyPath=%~f4
set deviceName=%5
set userTags=%6
set checkNameMode=%7

set CURDIR=%cd%
set PKGDIR=%~dp0..
set DAEMON=PdsClientsDaemon.exe
set subScript=start.bat

cd "%PKGDIR%\script"
call stop.bat

call :CreateDir "%logPath%"
call :CreateDir "%dataPath%"
call :CreateDir "%historyPath%"

set configPath=%dataPath%\config
call :DefaultConfig
call :CreateDir "%configPath%"

call :ExecSubScript "%subScript%"

cd "%PKGDIR%\script"
call upgrade.bat

cd /d "%CURDIR%"
echo "start daemon"
echo "%PKGDIR%\bin\%DAEMON%" -logPath="%logPath%" -dataPath="%dataPath%" -port=%port% -historyPath="%historyPath%"
start "%DAEMON%" /b "%PKGDIR%\bin\%DAEMON%" -logPath="%logPath%" -dataPath="%dataPath%" -port=%port% -deviceName=%deviceName% -historyPath="%historyPath%" -caller=script -userTags="%userTags%" -checkNameMode=%checkNameMode%
echo "start daemon done"
ENDLOCAL
goto :eof

:CreateDir
cd /d "%CURDIR%"
set dir=%1
if not exist %dir% (mkdir %dir%)
if not exist %dir% (echo failed to create directory %dir%)
goto :eof

:ExecSubScript
set script=%1
cd /d "%PKGDIR%\script"
for /D %%i in (*) do (
    cd /d %%i
    if exist %script% (
		echo %%i %script%
		call %script%
	)
    cd /d "%PKGDIR%\script"
)
cd /d "%CURDIR%"
goto :eof

:DefaultConfig
cd "%CURDIR%"
echo configPath=%configPath%
if exist "%configPath%" (goto :eof)
set defaultConfig=%PKGDIR%\config
echo defaultConfig="%defaultConfig%"
if exist "%defaultConfig%" (xcopy /s /y /i "%defaultConfig%" "%configPath%")
goto :eof