#!/bin/bash -eu
# SPDX-FileCopyrightText: 2025 Uwe Fechner, Bart van de Lint
# SPDX-License-Identifier: MIT

# Ensure the script runs from the project root
if [[ $(basename "$(pwd)") == "bin" ]]; then
    cd ..
fi

export JULIA_PKG_SERVER_REGISTRY_PREFERENCE=eager

julia_channel=""
if [[ "${1-}" == \+* ]]; then
    julia_channel="$1"
    julia_major="${1#+}"
else
    julia_major=$(julia --version | cut -d' ' -f3 | cut -d'.' -f1,2)
fi

# TODO: copy default manifest by default

# --- Find system image ---
branch=""
if git rev-parse --git-dir > /dev/null 2>&1; then
    branch=$(git rev-parse --abbrev-ref HEAD | sed 's/\//-/g')
fi
# Construct the system image path dynamically
SOFILE="bin/kps-image-${julia_major}.so"
if [[ -n "$branch" ]]; then
    SOFILE="bin/kps-image-${julia_major}-${branch}.so"
fi

# --- Execution logic ---
# Pass any remaining arguments ("$@") to the julia executable
if test -f "$SOFILE"; then
    echo "Found system image: $SOFILE"
    julia "$@" -J "$SOFILE" --project
else
    echo "No system image found, starting default Julia session"
    julia "$@" --project
fi
