:: Copyright (C) 2025 Axivion GmbH
:: Copyright (C) 2025 The Qt Company GmbH, a subsidiary of The Qt Group
:: https://www.qt.io

@echo off

setlocal

::set "BAUHAUS_PYTHON=C:\Program Files\Python37\python.exe"
::set "BAUHAUS_CONFIG="

:: set "AXIVION_BASE_DIR=C:\Program Files (x86)\Bauhaus"
for /f "delims=" %%p in ('where gravis') do set "AXIVION_BASE_DIR=%%~dpp.."

:: environment variable RACES controls the location of the races text file
if not defined RACES (
    set "RACES=%CD%\races.txt"
)

:: verify IR parameter
if "%1"=="" (
    echo Pass name of IR file as 1st parameter >&2
    exit /b 1
)
if not exist "%1" (
    echo Cannot find IR file %1 >&2
    exit /b 2
)
set "ir_file=%1"

:: verify optional RFG parameter
if "%2"=="" (
    set "rfg_file=%~dpn1.rfg"
    set create_rfg=1
) else (
    set "rfg_file=%2"
    set create_rfg=
)

:: disable StaticSemanticAnalysis if requested
if "%3"=="" (
    set "semantic_analysis=--rule StaticSemanticAnalysis"
) else if "%3" EQU 1  (
    set semantic_analysis=
)

:: check that configuration exists
if not defined BAUHAUS_CONFIG (
    echo Please set BAUHAUS_CONFIG to your project configuration with config for Parallelism-UnsafeVarAccess >&2
    exit /b 1
)
set enable_id_json=%~dp0enable_id_output.json
echo {"Analysis":{"Parallelism-UnsafeVarAccess":{"show_object_number": true}},"_Format":"1.0"} > %enable_id_json%
set "BAUHAUS_CONFIG=%enable_id_json%;%BAUHAUS_CONFIG%"
echo Using BAUHAUS_CONFIG=%BAUHAUS_CONFIG%

:: :: setup complete :: ::

:: run race analysis
echo Running Race Analysis writing into %RACES% >&2
if defined create_rfg (
    axivion_analysis --ir "%ir_file%" %semantic_analysis% --rule Parallelism-UnsafeVarAccess -o "%RACES%" --output_rfg "%rfg_file%"
) else (
    axivion_analysis --ir "%ir_file%" %semantic_analysis% --rule Parallelism-UnsafeVarAccess -o "%RACES%"
)
if errorlevel 1 (
    echo Stopped due to error %ERRORLEVEL% >&2
    exit /b %ERRORLEVEL%
)
:: output pdfs
echo Running Gravis to generate pdf files into %CD%\pdfs >&2
gravis --quit --script "%AXIVION_BASE_DIR%\example\scripts\create_callgraphs_pdf.py" "%rfg_file%"
if errorlevel 1 (
    echo Stopped due to error %ERRORLEVEL% >&2
    exit /b %ERRORLEVEL%
)
:: done
echo Done with call graph extraction >&2
