@echo off
setlocal EnableDelayedExpansion

:: Configuration section :::::::::::::::::::::::::::::::::::::::::::::::::::::::
set LOCAL_PATH=.\build
:: Path to HexView binary
set HEXVIEW=%LOCAL_PATH%\..\tools\HexView\hexview.exe

:: Output path
set OUTPUT=.

set DEV_PATH=%LOCAL_PATH%\out_files\dev\ec
set VBF_PATH=%LOCAL_PATH%\out_files\vbf\ec

set INPUT=%LOCAL_PATH%\out

:: Target address of ECU
set ECU_ADDRESS=0x1201

:: Enable creation of encryptef VBFs (ON, OFF)
set DEC_ENABLE=OFF

:: Enable creation of compressed VBFs (ON, OFF)
set CMPR_ENABLE=OFF

:: Set compression type (LZMA, FORD)
set CMPR_TYPE=FORD

set opt_level=9
set dict_size=4096


:: Logical block parameters
:: Start address and length of logical block, address of verification structure
:: Note: The parameters are chosen based on the file name which is checked
::       for occurrence of "B1", "B2".

:: Parameters of 1st logical block
set B1_ADDRESS=0x00400000
set B1_LENGTH=0x00200000
set B1_VS_ADDR=0x005F3E00
set B1_SEG_SIZE=256
set B1x=256

:: Parameters of 2nd logical block
set B2_ADDRESS=0x00500000
set B2_LENGTH=0x00100000
set B2_VS_ADDR=0x005FF000
set B2_SEG_SIZE=256
set B2x=256

:: Path to key files for signature calculation
set SIG_PARAM=%LOCAL_PATH%\..\tools\DemoKeys\key_dev.txt
set SIG_PARAM_DEV=%LOCAL_PATH%\..\tools\DemoKeys\key_dev.txt

:: End of configuration section ::::::::::::::::::::::::::::::::::::::::::::::::

:: Configuration check
if not defined B1_ADDRESS goto :ParamError
if not defined B1_LENGTH goto :ParamError
if not defined B1_VS_ADDR goto :ParamError
if not defined B1_SEG_SIZE goto :ParamError
if not defined B2_ADDRESS goto :ParamError
if not defined B2_LENGTH goto :ParamError
if not defined B2_VS_ADDR goto :ParamError
if not defined B2_SEG_SIZE goto :ParamError


:: Determine corresponding logical block
echo %~n1 | findstr "r" > nul && set BLOCK=B1

rem -----------------------------------------------------------------------------------------------
rem ----swlm partnumber start----
set part_input_swlm=%LOCAL_PATH%\..
set lineFlag=0

for /f "delims=*" %%i in (%part_input_swlm%\partno.txt) do (
	set /a lineFlag+=1
	if !lineFlag!==4 ( set Partno=%%i ) 
)

set Version_Geely=%Partno:~53,1%
set Partno_Geely=%Partno:~5,2%%Partno:~12,2%%Partno:~19,2%%Partno:~26,2%%Partno:~33,2%

if not "%Version_Geely%" == "" (
	if not "%Partno_Geely%" == "0000000000" (
		set SW_PART_NUMBER=%Partno_Geely%
		set SW_VERSION=%Version_Geely%
	)
)

::if not "%versno_Vol%" == "" (
::	if not "%Partno_Vol%" == "00000000" (
::		set SW_PART_NUMBER=%Partno_Vol%%versno_Vol%
::	)
)

rem -----------------------------------------------------------------------------------------------
::r
::set SW_PART_NUMBER=6608092623
set BLOCK=B1

:mergeFile
:: add Delete existing content
::del /f /q %DEV_PATH%\elf\*.*
::del /f /q %DEV_PATH%\map\*.*
::del /f /q %DEV_PATH%\s3\*.*
::del /f /q %VBF_PATH%\*.*
::del /f /q %VBF_PATH%\volvo\*.*

rd /s /q %LOCAL_PATH%\out_files\dev
rd /s /q %LOCAL_PATH%\out_files\vbf

:: add Build directory structure
md %DEV_PATH%\elf
md %DEV_PATH%\map
md %DEV_PATH%\s3
md %VBF_PATH%\
::md %VBF_PATH%\volvo

:: add Copy the generated files of each project to dev
copy %INPUT%\S32K312.elf .\%DEV_PATH%\elf
copy %INPUT%\S32K312.map .\%DEV_PATH%\map
copy %INPUT%\S32K312.lst .\%DEV_PATH%\map
copy %INPUT%\all.hex .\%DEV_PATH%\s3
::copy %INPUT%\r.vbf .\%VBF_PATH%\

::suo add create all hex file
::%HEXVIEW%  /S /MT:DemoBm.hex+DemoFbl.hex+rPP.hex /XI -o %OUTPUT%\out_files\hex\AllHex.hex

:: Change to current working path (drag & drop)
::cd /d %~d0%~p0

:: Create Hexview hexview-vbf.ini files
call :WriteVbf2 > %LOCAL_PATH%\hexview-vbf.ini


:: Create unprocessed vbf 2.6 container from input hex file
:: add create vbf file
%HEXVIEW% %INPUT%\all.hex /S /AD:!%BLOCK%x! /XVBF /VS /P:%LOCAL_PATH%\hexview-vbf.ini /E:%LOCAL_PATH%\hexview-vbf.log -o %VBF_PATH%\%SW_PART_NUMBER%%SW_VERSION%.vbf

:: Delete the following strings to generate a new file 
ren %VBF_PATH%\%SW_PART_NUMBER%%SW_VERSION%.vbf %SW_PART_NUMBER%%SW_VERSION%.txt
findstr /v /r /c:"//Development software signature" /c:"//software signature" /c:"sw_signature =" %VBF_PATH%\%SW_PART_NUMBER%%SW_VERSION%.txt > %VBF_PATH%\rename.txt
ren %VBF_PATH%\rename.txt %SW_PART_NUMBER%%SW_VERSION%.vbf
del %VBF_PATH%\%SW_PART_NUMBER%%SW_VERSION%.txt

:: Remove intermediate files
::echo Remove intermediate files
::del %INPUT%\all.hex
del %LOCAL_PATH%\hexview-vbf.ini
rem del %INPUT%/S32K312*


del SignDAL_PSS_SHA256.*

exit /b

:: *** Sub routines to create Hexview .ini files ******************************

:WriteVbf2
echo [VBFHEADER]
echo VBF_VERSION=2.6

echo DESCRIPTION=S32K312 update
echo SW_CALL_ADDRESS=%B4_ADDRESS%
echo SW_PART_NUMBER=%SW_PART_NUMBER%
echo SW_VERSION=%SW_VERSION%
echo SW_CURRENT_PART_NUMBER=
echo SW_CURRENT_VERSION=
echo SW_PART_TYPE=EXE


if ""=="" (
   echo DATA_FORMAT_ID=0x00
   echo DATPROC_METHOD=0
   echo DATPROC_PARAM=
)

echo ECU_ADDRESS=%ECU_ADDRESS%
if "%BLOCK%" =="B4" (
   echo ERASE_LIST_GEN_MODE=0
) else (
   echo ERASE_LIST_GEN_MODE=2
   echo ERASE_ADDRESS=!%BLOCK%_ADDRESS!
   echo ERASE_LENGTH=!%BLOCK%_LENGTH!
)
echo VS_ADDRESS=!%BLOCK%_VS_ADDR!
echo CHECKSUM_METHOD=19
echo SIGNATURE_METHOD=39
echo SIGNATURE_PARAM=%SIG_PARAM%
echo SIGNATURE_PARAM_DEV=%SIG_PARAM_DEV%
echo.
echo ; Verification Structure Attributes
echo Force32BitFormat=1
echo IdTagBeginLength=2
echo IdTagBegin=0000
echo IdTagEndLength=0
echo BlockChecksumType=20
echo CSUM_METHOD=20
exit /b

:: *** Sub routines to create lzma files ******************************
:: Compress the segments of a file using LZMA compression
:compress_lzma
 
set PROGRAMERR=0

echo Compress file using LZMA
echo ========================
echo Input file         : %1
echo Path to HexView    : %2
echo Path to LZMA       : %3
echo Optimization level : %4
echo Dictionary size    : %5

:: Create local variables
set workDrive=%~d0
set workDir=%~d0%~p0
set tempDir=%workDir%\temp\

set filePath=%~d1%~p1
set fileName=%~n1
set fileExt=%~x1

:: Create temporary directory
if not exist %tempDir% (
   mkdir %tempDir%
)

:: Clean temporary directory
del /q %tempDir%\*.*

:: Change working directory
%workDrive%
cd %workDir%

:: Copy input to temporary directory
copy %filePath%%fileName%%fileExt% %tempDir%%fileName%%fileExt%

:: Split files into segments
call :splitFiles %tempDir%%fileName%%fileExt% %2

:: Loop over files and compress them
del %filePath%%fileName%_lzma.hex
call :loopFiles %2 %3 %4 %5 %filePath%%fileName%_lzma.hex

:: Clean up variables
set workDrive=
set workDir=
set tempDir=

set filePath=
set fileName=
set fileExt=

:: End of main function
exit /b %PROGRAMERR%

:: Split files into binary segments
:splitFiles
%2 %1 /s /xsb /e:error.txt /o:%tempDir%\%filename%_split.bin
exit /b

:loopFiles
for %%f in (%tempDir%\%filename%_split_*.bin) do (
   :: file name, lzma tool, optimization level, dictionary size
   call :processFile %%f %2 %3 %4
   :: file name, hexview, output, split filename
   call :mergeFile %%f %1 %5 %filename%_split
)

exit /b

:processFile
echo Compress segment %1...
:: Compress the download file with LZMA
%2 -O%3 -ws=%4 %1 %1.lzma
exit /b

:mergeFile
echo Merge files into output file %3...
set mergePath=%~d1%~p1
set mergeName=%~n1
set mergeExt=%~x1

call set mergeAddr=%%mergeName:%4_=%%
echo Merging segment at 0x%mergeAddr%

if exist %3 (
   %2 %3 /MO:%1.lzma;0x%mergeAddr% /s /xi /E:error.txt /o:%3
) else (
   %2 /MO:%1.lzma;0x%mergeAddr% /s /xi /E:error.txt /o:%3
)


exit /b



:ParamError
echo.
echo ERROR: Parameter configuration incomplete!
echo.
pause
exit /b