@echo off
SetLocal EnableExtensions EnableDelayedExpansion

::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Copyright (c) 2024 Alexey Kuryakin daqgroup@mail.ru
::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Copy all *.exe files located near *.lpr projects to
:: corresponded target directory to have both platform
:: executables (Linux+Windows) in the same place.
::::::::::::::::::::::::::::::::::::::::::::::::::::::

::::::::::::::::::::::::::
:: DaqGroup Suite location
::::::::::::::::::::::::::
set SourceDir=%~dp0

::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Targer /home/$USER/projects/daqgroup/suite location
::::::::::::::::::::::::::::::::::::::::::::::::::::::
set TargetDir=t:\projects\daqgroup\suite\
set DeluxeDir=c:\opt\daqgroup\development\tools\fpcupdeluxe

:Main
pushd "%SourceDir%" && call :HandleAllLpr
popd
goto :EOF

:HandleAllLpr
call :CopyLhelp
for /f "tokens=* delims=" %%i in ('dir /b /s *.lpr') do call :HandleLpr "%%~fi"
goto :EOF

:HandleLpr
set "src=%~dpn1.exe" && set "dst="
for /f "tokens=* delims=" %%i in ('echo %src%^| unix replacestr "%SourceDir%" "%TargetDir%"') do set "dst=%%i"
if exist "%src%" if defined dst call :XCopyExe "%src%" "%dst%"
set "src=%~dpn1.dll" && set "dst="
for /f "tokens=* delims=" %%i in ('echo %src%^| unix replacestr "%SourceDir%" "%TargetDir%"') do set "dst=%%i"
if exist "%src%" if defined dst call :XCopyExe "%src%" "%dst%"
goto :EOF

:XCopyExe
if "%~1" == "" goto :EOF
if "%~2" == "" goto :EOF
if "%~1" == "%~2" goto :EOF
if not exist "%~dpnx1" == "" goto :EOF
if not exist "%~dp2" == "" goto :EOF
if exist "%~f1" unix strip -p "%~f1"
echo xcopy "%~1" "%~dp2" :
call xcopy /D /F /C /I /R /Y "%~1" "%~dp2"
goto :EOF

:CopyLhelp
for /f "tokens=* delims=" %%i in ('dir /b /s %DeluxeDir% ^| unix grep 'lhelp.exe'') do call :DoCopyLHelp "%%~i"
goto :EOF
:DoCopyLHelp
if "%~1" == "" goto :EOF
if not exist "%~f1" goto :EOF 
if not exist "%~dpn1.ico" goto :EOF 
if not exist "%~dp1.\languages" goto :EOF
if not exist "%TargetDir%\crwkit\add\src\lhelp\win32" goto :EOF
call xcopy /D /F /C /I /R /Y "%~f1" "%TargetDir%\crwkit\add\src\lhelp\win32\"
call xcopy /D /F /C /I /R /Y "%~dpn1.ico" "%TargetDir%\crwkit\add\src\lhelp\win32\"
call xcopy /D /F /C /I /R /Y "%~dp1.\languages\*.*" "%TargetDir%\crwkit\add\src\lhelp\win32\languages\"
goto :EOF
