#!/usr/bin/env bash

set -e  # Exit immediately if a command exits with a non-zero status

echo "Compile nifs, C and CPP sources in core"
make build -C nif_graph
make build -C kyoto

mkdir -p _beam  # Ensure the directory is created if it doesn't exist
if [ ! -f "_beam/refcore_gen_syn.beam" ] || [ ! -f "_beam/referl_misc.beam" ] || [ ! -f "_beam/refgen_scanc.beam" ]; then
    echo "Compiling *.yrl, *.erl, *.syntax files"
    erl -eval '{ok, _}=yecc:file("src/refcore_gen_syn.yrl", [verbose]), halt().' -noshell

    if [ -z "$REFERL_GEN_PATH" ]; then
        GEN_PATH="../referl_gen"
    else
        GEN_PATH="$REFERL_GEN_PATH"
    fi

    erlc -I ".." -o _beam src/refcore_gen_syn.erl "$GEN_PATH/src/referl_misc.erl" "$GEN_PATH/src/refgen_scanc.erl"
    erl -eval 'refcore_gen_syn:file("src/refcore_erlang.syntax", "src/refcore_erl_"), halt().' -noshell -pa "_beam"
else
    echo "Beam files already exist for *.yrl, *.erl, *.syntax files, skipping compilation."
fi

echo "Done."