#!/bin/bash
# Copyright (C) 2025 Axivion GmbH
# Copyright (C) 2025 The Qt Company GmbH, a subsidiary of The Qt Group
# https://www.qt.io

set -e

#export BAUHAUS_PYTHON=
#export BAUHAUS_CONFIG=

AXIVION_BASE_DIR="$(dirname "$(dirname "$(readlink -f "$(which gravis)")")")"

if [ ! -d "$AXIVION_BASE_DIR" ]; then
    echo "Could not find out where Axivion Suite is installed" >&2
    exit 2
fi

if [ "$RACES" == "" ]; then
    RACES="$PWD/races.txt"
fi
export RACES

# Load IR file provided as 1st parameter
if [ $# -lt 1 ]; then
   echo "Pass name of IR file as 1st parameter" >&2
   exit 1
fi
ir_file="$1"
if [ ! -r "$ir_file" ]; then
   echo "Cannot find IR $ir_file" >&2
   exit 2
fi

# Optionally create RFG with exact name
if [ $# -ge 2 ]; then
    rfg_file="$2"
    output_rfg_option=""
else
    rfg_file="$(basename "$ir_file" .ir).rfg"
    output_rfg_option="--output_rfg $rfg_file"
fi

# disable StaticSemanticAnalysis if requested
if [ "$3" == "" ]; then
    semantic_analysis="--rule StaticSemanticAnalysis"
else
    semantic_analysis=""
fi

# check that we have a project configuration
if [ "$BAUHAUS_CONFIG" == "" ]; then
    echo "Please set BAUHAUS_CONFIG to your project configuration with config for Parallelism-UnsafeVarAccess" >&2
    exit 1
fi
enable_id_json="$(mktemp --suffix=.json)"
echo '{"Analysis":{"Parallelism-UnsafeVarAccess":{"show_object_number": true}},"_Format":"1.0"}' > "$enable_id_json"
export BAUHAUS_CONFIG="$enable_id_json:$BAUHAUS_CONFIG"
echo "Using BAUHAUS_CONFIG=$BAUHAUS_CONFIG"



# setup complete

echo "Running Race Analysis writing into $RACES" >&2

axivion_analysis --ir "$ir_file" $semantic_analysis --rule Parallelism-UnsafeVarAccess -o "$RACES" $output_rfg_option

echo "Running Gravis to generate pdf files into $PWD/pdfs" >&2
gravis --quit --script "$AXIVION_BASE_DIR/example/scripts/create_callgraphs_pdf.py" "$rfg_file"

rm -f "$enable_id_json"
echo "Done with call graph extraction" >&2
