@ECHO OFF
REM This file was generated by 'ProgGenerator'  

REM Build script to compile an ESP32 for the MobaLedLib by Juergen
REM
REM When the script is called the first time all libraries have to be compiled
REM This will take up to 3 minutes. When the ESP is updated the next time only
REM the changed files have to be processed which will speed up the build process
REM dramatically

REM Optional parameters:
REM   rebuild     Rebuilds all (will take up to 3 minutes)
REM   download    Send the hex file to the ESP


CHCP 65001 >NUL

set ArduinoLib=C:\Users\harol\Documents\Arduino/libraries
if not exist MyPrivateBuildScript.cmd (
       REM embedded Fast Build and Upload
       call :build "C:\Program Files (x86)\Arduino\" "LEDs_AutoProg.ino" COM7 "esp32:esp32:esp32:PSRAM=disabled,PartitionScheme=default,CPUFreq=240,FlashMode=qio,FlashFreq=80,FlashSize=4M,UploadSpeed=921600,DebugLevel=none" 115200  "%ArduinoLib%" esp32 %*
) else (
       REM user defined Build and Upload
       call MyPrivateBuildScript.cmd "C:\Program Files (x86)\Arduino\" "LEDs_AutoProg.ino" COM7 "--board esp32:esp32:esp32:PSRAM=disabled,PartitionScheme=default,CPUFreq=240,FlashMode=qio,FlashFreq=80,FlashSize=4M,UploadSpeed=921600,DebugLevel=none" 115200  "%ArduinoLib%" esp32 %*
       )
IF ERRORLEVEL 1 ECHO Start_Arduino_Result: %ERRORLEVEL% > "Start_Arduino_Result.txt"
goto :eof



:build
REM                                                                           **** ToDo: Aktualisieren ***
REM Compile and flash time for ESP 14 sec on Hardis laptop
REM
REM
REM This file could be modified by the user to support special compiler switches
REM It is called if the switch the "Schnelles Build und Upload verwenden:" in the 'Config' sheet is enabled
REM
REM Parameter:               Example
REM  1: Arduino EXE Path:    "C:\Program Files (x86)\Arduino\"
REM  2: Ino Name:            "LEDs_AutoProg.ino"
REM  3: Com port:            "COM3"
REM  4: Build options:       "arduino:avr:nano:cpu=atmega328"
REM  5: Baudrate:            "57600" or "115200"
REM  6: Arduino Library path "%USERPROFILE%\Documents\Arduino\libraries"
REM  7: CPU type:            "atmega328p, atmega4809, esp32"
REM  8: options:             "noflash|norebuild"
REM  additional argument from caller
REM
REM The program uses the captured and adapted command line from the Arduino IDE
REM

SET aHome=%~1
SET fqbn=%~4
SET lib=%~6
SET ESP32_BOARD_VERSION=1.0.4
SET ESP32_TOOL_VERSION=2.6.1

call :short aTemp "%USERPROFILE%\AppData\Local\Temp\pyMobaLedLib_build\ESP32"
SET aCache=%aTemp%\cache
call :short packages "%USERPROFILE%\AppData\Local\Arduino15\packages"
if not exist "%aTemp%\Sketch"  md "%aTemp%\Sketch"
if not exist "%aCache%" md "%aCache%"

SetLocal EnableDelayedExpansion

copy "..\LEDs_AutoProg\LEDs_AutoProg.h" "%aTemp%\Sketch" >nul:
if errorlevel 1 (
   echo can't copy ..\LEDs_AutoProg\LEDs_AutoProg.h to build folder
   exit /b 1
   )

call ::getDirectory headerDir ..\LEDs_AutoProg\LEDs_AutoProg.h
call ::getDirectory sketchDir %2

if not "%headerDir%"=="%sketchDir%" (
   REM Necessary for rebuild         11.11.20:
   copy "..\LEDs_AutoProg\LEDs_AutoProg.h" . >nul:
   if errorlevel 1 (
      echo can't copy ..\LEDs_AutoProg\LEDs_AutoProg.h to actual dir
      exit /b 1
      )
)
REM !! developer option copy additional files !!
if exist AdditionalBuildFiles.txt (
   echo updating extra files
   for /F %%f in (AdditionalBuildFiles.txt) do (
      if exist "%%f" (
             echo update file %%f
             copy "%%f" "%aTemp%\Sketch" >nul:
             if errorlevel 1 (
                echo can't copy %%file to build folder
                exit /b 1
             )
      ) else (
             echo Additional build file '%%f' not found
             pause
             )
      )
)

rem check if prebuild targets exist and the current ino isn't newer
set srcFile=%~2
set cppFile=%aTemp%\sketch\%srcFile%.cpp

copy "%srcFile%" "%cppFile%" /Y >nul:

if exist "%aTemp%\rebuildFailed.txt" (
   echo Last rebuild failed ;-(
   goto :rebuild
   )

rem if the pre-build files are not there we need to do a complete new build
if not exist "%cppFile%" (
   echo CPP File "%cppFile%" does'n exist, rebuild ...
   goto :rebuild
   )

if "%8"=="rebuild" (
   echo Rebuild called from the command line
   goto :rebuild
   )

if "%8"=="flash" (
   goto :download
   )

rem now get date/time of both files to see if time is equal
FOR /F "tokens=* USEBACKQ" %%F IN (`forfiles /p "%atemp%\sketch" /m "%srcFile%.cpp" /C "cmd /c echo @fdate @ftime"`) DO SET DATE1=%%F
FOR /F "tokens=* USEBACKQ" %%F IN (`forfiles /m "%srcFile%" /C "cmd /c echo @fdate @ftime"`) DO SET DATE2=%%F

echo %srcFile%.cpp has date %date1%
echo %srcFile% has date %date2%

rem if equal then srcfile isn't newer
IF "%DATE1%"=="%DATE2%" goto fastbuild

rem now get the newest file
rem to compare, both file must be in same directory
copy "%srcFile%" "%aTemp%\sketch\" >nul:
FOR /F %%i IN ('DIR /B /O:D "%cppFile%" "%aTemp%\sketch\%srcFile%"') DO SET NEWEST=%%i
del "%aTemp%\sketch\%srcFile%" >nul:

rem check which file is newer, if source is new we need to run a arduino build to recreate the .ino.cpp file
if "%NEWEST%"=="%srcFile%" (
   echo New file detected "%NEWEST%", rebuild...
   goto :rebuild
   ) 
ECHO Newer file is %NEWEST%

goto :fastbuild

:getDirectory <resultVar> <pathVar>
(
    set "%~1=%~d2%~p2"
    goto :eof
)

:getShortName <resultVar> <filename>
(
    set %~1=%~s2
    goto :eof
)

:fastbuild
echo Running fastbuild
call Fastbuild.cmd %8
if errorlevel 1 (
    rem use argument norebuild to avoid rebuild in this case of build error
    set rebuild=1    if ""%8""==""norebuild"" set rebuild=0    if ""%8""==""additional"" set rebuild=0    if "%rebuild%"=="1" (
        rem in case that FastBuild.cmd returned errolevel 9 also a rebuild won't help
        if not errorlevel 9 (
            echo Fastbuild failed, trying a rebuild...
            goto rebuild
        )
    )
)

goto download

:rebuild
echo/
echo Running rebuild... Be patient, this will take up to 3 minutes ;-(((
echo/
if exist "%aTemp%" del "%aTemp%" /s/q >nul:
if exist "%aTemp%\link.cmd" del "%aTemp%\link.cmd"
:build
echo %date% > "%aTemp%\rebuildFailed.txt"

REM *** Call the arduino builder ***
call :write "%aHome%\arduino-builder" -compile -logger=human ^
     -hardware "%packages%" ^
     -tools "%aHome%\tools-builder" ^
     -tools "%aHome%\hardware\tools\avr" ^
     -built-in-libraries "%aHome%\libraries" -libraries "%LIB%" ^
     -fqbn=%fqbn% -build-path "%aTemp%" ^
     -warnings=default ^
     -build-cache "%aCache%" ^
     -prefs=build.warn_data_percentage=75 ^
     -prefs=runtime.tools.avrdude.path="%aHome%\hardware\tools\avr" ^
     -prefs=runtime.tools.avr-gcc.path="%aHome%\hardware\tools\avr" >"%aTemp%\compile.cmd"

if exist AdditionalBuildOptions.txt (
  for /F "delims=" %%i in (AdditionalBuildOptions.txt) do call :write %%i >>"%aTemp%\compile.cmd"
)
call :write %srcFile% >>"%aTemp%\compile.cmd"

call "%aTemp%\compile.cmd"
if not errorlevel 1 (
  if exist "%aTemp%\rebuildFailed.txt" del "%aTemp%\rebuildFailed.txt" >nul:
)

:download
if "%8"=="noflash" goto :EOF
if not errorlevel 1 (
   set uploadTo=%3
   if not "%target%"=="" set uploadTo=%target%
   echo Uploading to !uploadTo!

   REM *** Flash program ***
   if "!uploadTo:~0,3!"=="COM" (
          "%packages%\esp32\tools\esptool_py\%ESP32_TOOL_VERSION%/esptool.exe" --chip esp32 --port \\.\!uploadTo! --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect  0xE000  "%packages%\esp32\hardware\esp32\%ESP32_BOARD_VERSION%/tools/partitions/boot_app0.bin" 0x1000  "%packages%\esp32\hardware\esp32\%ESP32_BOARD_VERSION%/tools/sdk/bin/bootloader_qio_80m.bin" 0x10000 "%aTemp%\%srcFile%.bin" 0x8000  "%aTemp%\%srcFile%.partitions.bin"
   ) else (
          "%packages%\esp32\hardware\esp32\%ESP32_BOARD_VERSION%/tools/espota.exe" -i !uploadTo! -p 3232 --auth= -f "%aTemp%\%srcFile%.bin"
          )
    REM *** caller expects a positive errorlevel in error case, but ESPTOOL returns errorlevel -1
    if not errorlevel 0 exit /b 1

)
Goto :EOF

:: write a text without newline
:write
echo | set /p x="%* "
goto :eof

:short
set %1=%~s2
goto :eof

