#!/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

USE_KAIMON=false

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

# Kaimon integration requires Julia >= 1.12
if [[ $julia_major != "1.11" ]]; then
    if command -v ss &> /dev/null; then
        if ss -ltn '( sport = :2828 )' | grep -q ':2828'; then
            USE_KAIMON=true
        fi
    elif command -v lsof &> /dev/null; then
        if lsof -nP -iTCP:2828 -sTCP:LISTEN &> /dev/null; then
            USE_KAIMON=true
        fi
    fi
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
SOFILE="bin/kps-image-${julia_major}.so"

julia_init='using Revise; '
if [[ "$USE_KAIMON" == "true" ]]; then
    julia_init+='using Kaimon; Gate.serve(); '
fi
julia_init+='using KiteModels; function menu(); include("examples/menu.jl"); end'

# Build launch arguments once for primary and fallback execution paths.
JULIA_ARGS=("+${julia_major}" -t 1 $GCT --project -i -e "$julia_init")
if test -f "$SOFILE"; then
    echo "Found system image!"
    JULIA_ARGS=("+${julia_major}" -J "$SOFILE" -t 1 $GCT --project -i -e "$julia_init")
fi

# Run Julia with setup_env overrides first, then retry once with a clean loader env.
set +e
julia "${JULIA_ARGS[@]}"
_jl_rc=$?
set -e
if [[ $_jl_rc -ne 0 ]]; then
    echo "Julia launcher exited with code ${_jl_rc}. Retrying once without LD_PRELOAD/LD_LIBRARY_PATH overrides..." >&2
    env -u LD_PRELOAD -u LD_LIBRARY_PATH command julia "${JULIA_ARGS[@]}"
fi