#!/bin/bash

if [[ $(basename $(pwd)) == "bin" ]]; then
    cd ..
fi

export NO_AT_BRIDGE=1
export JULIA_PKG_SERVER_REGISTRY_PREFERENCE=eager

if [[ "$(uname -s)" == "Darwin" ]]; then
    # Avoid Tk backend issues on macOS (e.g. non-responsive close button in PyPlot windows).
    # Keep user override if MPLBACKEND is already set.
    if [[ -z "${MPLBACKEND:-}" ]]; then
        export MPLBACKEND=qtagg
    fi
fi

. ./bin/setup_env

if command -v nproc &> /dev/null; then
    FAST_CORES=$(($(nproc) / 2 - 1))
else
    FAST_CORES=3 # default value
fi

GCT="--gcthreads=4,1"
export JULIA_PKG_SERVER_REGISTRY_PREFERANCE=eager

julia_version=$(julia --version | awk '{print($3)}')
julia_major=${julia_version:0:3} 
if [[ $julia_major == "1.1" ]]; then
    julia_major=${julia_version:0:4}
else
    GCT=""
fi

# Check that the current Julia version matches the one used during install
if [[ -f "install_version_${julia_major}.txt" ]]; then
    install_version=$(cat "install_version_${julia_major}.txt")
    if [[ "$julia_version" != "$install_version" ]]; then
        echo -e "\033[1;31mWarning:\033[0m The Julia version has changed (installed: $install_version, current: $julia_version)."
        echo "Please run bin/install again!"
        exit 1
    fi
fi
if [[ $HOSTNAME == "ufryzen" || $HOSTNAME == "framework" ]]; then
    export NO_MTK=true
fi
if [ -d ".git" ]; then
    branch=$(git rev-parse --abbrev-ref HEAD)
else
    branch=""
fi

script_file=""
if [[ $# -gt 0 ]]; then
    script_file="$1"
    shift
    if [[ ! -f "$script_file" ]]; then
        echo "Error: script file '$script_file' not found."
        exit 1
    fi
fi

if test -f "bin/kps-image-${julia_major}.so"; then
    echo "Found system image!"
    if [[ -n "$script_file" ]]; then
        PLOT=1 julia -J bin/kps-image-${julia_major}.so -t 1 $GCT --project "$script_file" "$@"
    else
        PLOT=1 julia -J bin/kps-image-${julia_major}.so -t 1 $GCT --project -i -e 'using KiteControllers; test_menu() = Base.include(Main, joinpath(pkgdir(KiteControllers), "test", "test_menu.jl")); menu_learning() = Base.include(Main, joinpath(pkgdir(KiteControllers), "examples", "menu_learning.jl"))'
    fi
else
    if [[ -n "$script_file" ]]; then
        PLOT=1 julia --project -t 1 $GCT "$script_file" "$@"
    else
        PLOT=1 julia --project -t 1 $GCT -i -e 'using KiteControllers; test_menu() = Base.include(Main, joinpath(pkgdir(KiteControllers), "test", "test_menu.jl")); menu_learning() = Base.include(Main, joinpath(pkgdir(KiteControllers), "examples", "menu_learning.jl"))'
    fi
    # julia --project
fi
