#!/bin/sh

set -e

if [ -z "${APPIMAGE}" ]; then
    self=$(readlink -f -- "$0")
    export APPDIR="${self%/*}"
fi

# uv creates opt/python as a symlink or directory — resolve to the real cpython dir
PYTHON_DIR=$(find "${APPDIR}/opt" -maxdepth 1 -type d -name "cpython-*" | head -1)
PYTHON_DIR="${PYTHON_DIR:-${APPDIR}/opt/python}"
PYTHON="${PYTHON_DIR}/bin/python3"

export SCIQLOP_BUNDLED="1"
export SSL_CERT_FILE=$($PYTHON -c "import certifi; print(certifi.where())")
export PATH="${APPDIR}/opt/uv:${PYTHON_DIR}/bin:${APPDIR}/usr/local/bin:${PATH}"

############################################
# Handle AppImage built-in commands first
############################################

case "$1" in
    --appimage-extract|--appimage-mount|--appimage-version)
        exec "$APPIMAGE" "$@"
        ;;
esac

############################################
# Subcommands
############################################

case "$1" in
    python) shift; exec "$PYTHON" "$@" ;;
    uv)     shift; exec "${APPDIR}/opt/uv/uv" "$@" ;;
    shell)  exec /bin/sh ;;
esac

############################################
# Handle re-entry as Python interpreter
# (venv symlinks python → AppImage binary)
############################################

case "$1" in
    -c|-m|-V|--version|-W|-X|-h|--help|-I|-s|-u|-v|-E|-B|-O)
        exec "$PYTHON" "$@"
        ;;
esac

############################################
# Default: launch SciQLop
############################################

#export SCIQLOP_DEBUG="1"
exec "$PYTHON" -I -m SciQLop.app "$@"
