#!/bin/bash

COMPILETYPE="Debug"
ROOTPATH=$(pwd)
INSTALLDIR="${ROOTPATH}/aidge/install"
export AIDGE_INSTALL=$INSTALLDIR
DOTEST=ON

# Initialize an empty array to store the directory names
ordered_list=("aidge/aidge_core" "aidge/aidge_backend_cpu" "aidge/aidge_onnx")
available_module_list=()
module_to_compile_list=()

add_to_unique_list() {
    local arg=$1
    if [[ ! " ${module_to_compile_list[@]} " =~ " aidge/aidge_$arg " ]]; then
        module_to_compile_list+=("aidge/aidge_$arg")
    fi
}

# get the list of available modules
 while IFS= read -r -d '' dir; do
    # Get the second part of the directory name
    # Assuming directory names are in the format: aidge/aidge_<module_name>
    # name="${dir#aidge/aidge_}"

    # Add the name to the array
    available_module_list+=("$dir")
done < <(find aidge -maxdepth 1 -type d -name "aidge_*" -print0)

# get the list of modules to compute
if [ "$#" -eq 0 ] || { [ "$#" -eq 1 ] && [ "$1" == "Release" ]; }; then
    module_to_compile_list=("${available_module_list[@]}")
else
    for i in "$@"; do
        if [ "$i" == "Release" ]; then
            COMPILETYPE="Release"
            DOTEST=OFF
        elif [ "$i" == "core" ]; then
            add_to_unique_list "core"
        elif [ "$i" == "backend_cpu" ]; then
            add_to_unique_list "core"
            add_to_unique_list "backend_cpu"
        elif [ "$i" == "onnx" ]; then
            add_to_unique_list "core"
            add_to_unique_list "backend_cpu"
            add_to_unique_list "onnx"
        else
            echo "unknown option '$i'"
        fi
    done
fi

# Print the list of extracted names
echo "The following modules will be compiled:"
for name in "${module_to_compile_list[@]}"; do
    echo "${name}"
done

mkdir -p ${INSTALLDIR}

for module_name in "${ordered_list[@]}"; do
    if [[ " ${module_to_compile_list[@]} " =~ " $module_name " ]]; then
        if [ -n "$(find ${module_name} -maxdepth 1 -type f -name "CMakeLists.txt" -print)" ]; then
            mkdir -p ${module_name}/build
            cd ${module_name}/build/
            cmake -DCMAKE_INSTALL_PREFIX:PATH=${INSTALLDIR} -DCMAKE_BUILD_TYPE=${COMPILETYPE} -DWERROR=OFF -DPYBIND=OFF -DTEST=${DOTEST} ${@} ..
            make all install -j20
            if [[ "$COMPILETYPE" == "Debug" ]]; then
                ctest --output-on-failure || true
            fi
            cd ${ROOTPATH}
        fi
        if [ -n "$(find ${module_name} -maxdepth 1 -type f -name "setup.py" -print)" ]; then
            echo "Compiling a python module ${module_name}"
            # python ${module_name}/setup.py
        fi
    fi
done