@echo off
setlocal enabledelayedexpansion

REM Define the header file path and the template file path
set headerFile=common\build\release.h
set templateFile=manifest_template.json
set manifestFile=%1%
set keyName=HKLM\SOFTWARE\WOW6432Node\innovaphone\innovaphoneSDK\
set valueName="Company"
set BUILD=%2%
set APPSERVICEID=%3%
set MANUFACTURER=%4%
if "%~5"=="" (
    set ASAN=0
) else (
    set ASAN=%~5
)
REM ensure that the system32 folder is inside the PATH for findstr
set PATH=%windir%\system32;%PATH%

if not defined MANUFACTURER (
    for /f "tokens=3* delims= " %%a in ('REG QUERY HKLM\SOFTWARE\WOW6432Node\innovaphone\innovaphoneSDK\ /v CompanySDK 2^>nul') do (
        set MANUFACTURER=%%a %%b
    )
    if "!MANUFACTURER:~-1!"==" " (
        set "MANUFACTURER=!MANUFACTURER:~0,-1!"
    )
    if not defined MANUFACTURER (
        set MANUFACTURER=Unknown
    )        
)
REM Strip any quotes that might be there
set MANUFACTURER=%MANUFACTURER:"=%
set MANUFACTURER_LOWER=%MANUFACTURER%

REM lowercase MANUFACTURER_LOWER
for %%a in ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i" "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r" "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z" "Ä=ä" "Ö=ö" "Ü=ü") do (  
    set "MANUFACTURER_LOWER=!MANUFACTURER_LOWER:%%~a!"  
)

REM Check if MANUFACTURER contains "innovaphone" or "CommunityLab"
echo %MANUFACTURER_LOWER% | findstr /i "innovaphone" >nul
set HAS_INNOVAPHONE=%ERRORLEVEL%

echo %MANUFACTURER_LOWER% | findstr /i "communitylab" >nul
set HAS_COMMUNITYLAB=%ERRORLEVEL%

if not %HAS_INNOVAPHONE%==0 if not %HAS_COMMUNITYLAB%==0 (
    set APPSERVICEID=%MANUFACTURER_LOWER%-%APPSERVICEID%
)

REM Extract values from the header file
for /f "tokens=3 delims= " %%a in ('findstr /c:"#define RELEASE_STATE" %headerFile%') do set RELEASE_STATE_MANIFEST=%%a
for /f "tokens=3 delims= " %%a in ('findstr /c:"#define VERSION_STR_MAJOR" %headerFile%') do set VERSION_STR_MAJOR=%%a

REM Remove quotes from the extracted values
set RELEASE_STATE_MANIFEST=%RELEASE_STATE_MANIFEST:"=%
set VERSION_STR_MAJOR=%VERSION_STR_MAJOR:"=%

if %ASAN%==1 (
    set RELEASE_STATE_MANIFEST=%RELEASE_STATE_MANIFEST% ASAN
)

REM Create JSON structure
set JSON_DATA={"appServiceId":"%APPSERVICEID%","manufacturer":"%MANUFACTURER%","version":{"id":"%VERSION_STR_MAJOR%","build":"%BUILD%","label":"%RELEASE_STATE_MANIFEST%"}

REM Check if the template file exists
if exist %templateFile% (
    REM Read the JSON file line by line
    for /f "usebackq delims=" %%a in ("%templateFile%") do (
        set line=%%a
        REM Append the line to the JSON_TEMPLATE variable
        set JSON_TEMPLATE=!JSON_TEMPLATE!%%a
    )

    REM Combine both parts
    set JSON_OUTPUT=!JSON_DATA!,!JSON_TEMPLATE!}
) else (
    REM If template does not exist, use the extracted JSON data directly
    set JSON_OUTPUT=!JSON_DATA!}
)

REM Write the combined JSON to output.json
echo !JSON_OUTPUT! > %manifestFile%

echo JSON file created successfully: %manifestFile%

endlocal