#!/bin/bash -eu
# SPDX-FileCopyrightText: 2025 Uwe Fechner
# SPDX-License-Identifier: MIT

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

export JULIA_PKG_SERVER_REGISTRY_PREFERENCE=eager

# Use the Qt (qtagg) backend on macOS and Linux to avoid Tk backend issues
# (e.g. non-responsive close button). Keep any user-set override.
if [[ "$(uname -s)" == "Darwin" || "$(uname -s)" == "Linux" ]]; then
    if [[ -z "${MPLBACKEND:-}" ]]; then
        export MPLBACKEND=qtagg
    fi
fi

. ./bin/setup_env

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} 
fi

if [ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1 ; then
    branch=$(git rev-parse --abbrev-ref HEAD | sed 's/\//-/g')
else
    branch=""
fi

if [[ $HOSTNAME == "ufryzen" || $HOSTNAME == "framework" ]]; then
    GCT="--gcthreads=8,1"
    # export NO_MTK=true
    # export USE_V9=true
else
    GCT="--gcthreads=4,1"
fi

# Determine system image filename based on branch
if [[ -n "$branch" ]]; then
    SOFILE="bin/kps-image-${julia_major}-${branch}.so"
else
    SOFILE="bin/kps-image-${julia_major}.so"
fi

# Run Julia with or without system image
if test -f "$SOFILE"; then
    echo "Found system image!"
    julia +${julia_major} -J "$SOFILE" -t 1 $GCT --project -i -e 'using KiteModels; function menu(); include("examples/menu.jl"); end'
else
    julia +${julia_major} -t 1 $GCT --project -i -e 'using KiteModels; function menu(); include("examples/menu.jl"); end'
fi