#!/bin/bash

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

# export MPLBACKEND=qt5agg
export QT_QPA_PLATFORM=xcb
export NO_AT_BRIDGE=1

if [[ "$(uname -s)" == "Linux" ]]; then
    export FONTCONFIG_FILE=/etc/fonts/fonts.conf
    # Preload Julia-bundled libraries to avoid version conflicts with older system libs.
    _PRELOADS=()
    _BUNDLED=$(find ~/.julia/artifacts -maxdepth 3 -name "libcrypto.so.3" -path "*/lib/*" 2>/dev/null | head -1); [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    # Preload libintl and libiconv before libglib (libglib depends on both; system versions may be missing).
    _BUNDLED=$(find ~/.julia/artifacts -maxdepth 3 -name "libintl.so.8" -path "*/lib/*" 2>/dev/null | head -1); [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    _BUNDLED=$(find ~/.julia/artifacts -maxdepth 3 -name "libiconv.so.2" -path "*/lib/*" 2>/dev/null | head -1); [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    # Pick the glib that exports g_string_copy (needed by libgobject >= 2.75).
    _BUNDLED=""
    for _gl in $(find ~/.julia/artifacts -maxdepth 3 -name "libglib-2.0.so.0" -path "*/lib/*" 2>/dev/null); do
        if nm -D "$_gl" 2>/dev/null | grep -q g_string_copy; then
            _BUNDLED="$_gl"
            break
        fi
    done
    [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    # Pick the fontconfig that exports FcConfigSetDefaultSubstitute (needed by Pango >= 1.57).
    _BUNDLED=""
    for _fc in $(find ~/.julia/artifacts -maxdepth 3 -name "libfontconfig.so.1" -path "*/lib/*" 2>/dev/null); do
        if nm -D "$_fc" 2>/dev/null | grep -q FcConfigSetDefaultSubstitute; then
            _BUNDLED="$_fc"
            break
        fi
    done
    [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    if [[ ${#_PRELOADS[@]} -gt 0 ]]; then
        export LD_PRELOAD=$(IFS=:; echo "${_PRELOADS[*]}")
    fi
    unset _PRELOADS _BUNDLED
fi

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
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}-${branch}.so"; then
    echo "Found system image!"
    if [[ -n "$script_file" ]]; then
        PLOT=1 julia -J bin/kps-image-${julia_major}-${branch}.so -t 1 $GCT --project "$script_file" "$@"
    else
        PLOT=1 julia -J bin/kps-image-${julia_major}-${branch}.so -t 1 $GCT --project -i -e 'using KiteControllers'
    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'
    fi
    # julia --project
fi
