@echo off
setlocal disabledelayedexpansion
call :start %*
goto :eof

:start

rem --- Get parameters of the project and the build ---------------------------
call "%~dp0prepare.bat" %*

rem --- Find FAR directory ----------------------------------------------------
set fardir=
if exist ".\far%far%\far.exe" (
  set fardir=.\far%far%
) else if exist "%exedir%\far%far%\far.exe" (
  set fardir=%exedir%\far%far%
) else if exist "%releasedir%\far%far%\far.exe" (
  set fardir=%releasedir%\far%far%
) else if exist "%srcdir%\far%far%\far.exe" (
  set fardir=%srcdir%\far%far%
) else if exist "%releasedir%\..\far%far%\far.exe" (
  set fardir=%releasedir%\..\far%far%
) else (
  echo Can't find FAR Manager
  exit 1
)
set plugindir=%fardir%\plugins\%project%

echo Params: %*
echo FAR directory: %fardir%
echo Plugin directory: %plugindir%

rem --- Create plugin directory if not present --------------------------------
if not exist "%plugindir%\." mkdir "%plugindir%\."

rem --- Build the plugin ------------------------------------------------------
if exist "%exedir%\%project%%ext%" del "%exedir%\%project%%ext%"
if exist "far.log" del "far.log"
setlocal
call "build" %*
if errorlevel 1 exit 1
if not exist "%exedir%\%project%%ext%" exit 1
endlocal

rem --- Copy the plugin to FAR's directory ------------------------------------
if exist "%plugindir%\%project%%ext%" del "%plugindir%\%project%%ext%"
if exist "%plugindir%\%project%%ext%.log" del "%plugindir%\%project%%ext%.log"
if exist "%plugindir%\*.lng" del "%plugindir%\*.lng"
copy "%exedir%\%project%%ext%" "%plugindir%" >nul
if errorlevel 1 exit 1
if exist "%exedir%\*.lng" copy "%exedir%\*.lng" "%plugindir%" >nul
if errorlevel 1 exit 1

rem --- Run FAR Manager -------------------------------------------------------
start /w "FAR Manager - test" "%fardir%\far.exe"

rem --- If a log file exists, copy it here ------------------------------------
if exist "%plugindir%\%project%%ext%.log" copy "%plugindir%\%project%%ext%.log" . >nul

rem --- Finished --------------------------------------------------------------
goto :eof
