#!/bin/sh
# dockmaster launcher.
#
# Resolves a Python interpreter that can actually import PyGObject, rather than
# trusting /usr/bin/python3. On this host that distinction matters: python3 is
# pinned via update-alternatives to 3.11 while the distro's compiled extensions
# in /usr/lib/python3/dist-packages target CPython 3.10, so `import gi` fails
# under the default interpreter.
#
# Unlike a pure GUI app, dockmaster has headless modes (--text, --json,
# --list-checks, --df) that never import gi. So a missing GTK is not fatal here:
# if no interpreter can import GTK4, we still hand off to a plain python3 and let
# app.py print the diagnostic only when a GUI was actually asked for. Exiting
# here would make `dockmaster --text` unusable on a headless box, which is
# exactly where it is most useful.
#
# Override the choice with DOCKMASTER_PYTHON=/path/to/python3.

set -eu

SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")
# This script lives in bin/; the importable package sits one level up.
ROOT=$(dirname "$(dirname "$SELF")")

GTK_PROBE='
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Gtk, Adw
'

# The package needs nothing beyond a modern-enough stdlib; 3.9 is the floor
# because of PEP 604 unions under `from __future__ import annotations` plus
# dict-ordering and dataclass behaviour the code relies on.
BASE_PROBE='
import sys
raise SystemExit(0 if sys.version_info >= (3, 9) else 1)
'

runs() {
    [ -n "${1:-}" ] || return 1
    command -v "$1" >/dev/null 2>&1 || return 1
    "$1" -c "$2" >/dev/null 2>&1
}

CANDIDATES="/usr/bin/python3 \
/usr/bin/python3.13 /usr/bin/python3.12 /usr/bin/python3.11 \
/usr/bin/python3.10 /usr/bin/python3.9 \
python3"

CHOSEN=""

# An explicit override always wins, and fails loudly rather than falling back.
if [ -n "${DOCKMASTER_PYTHON:-}" ]; then
    if runs "$DOCKMASTER_PYTHON" "$BASE_PROBE"; then
        CHOSEN="$DOCKMASTER_PYTHON"
    else
        echo "dockmaster: DOCKMASTER_PYTHON=$DOCKMASTER_PYTHON is not a usable Python 3.9+." >&2
        exit 1
    fi
fi

# Prefer an interpreter that can do everything, GUI included.
if [ -z "$CHOSEN" ]; then
    for candidate in $CANDIDATES; do
        if runs "$candidate" "$GTK_PROBE"; then
            CHOSEN="$candidate"
            break
        fi
    done
fi

# No GTK anywhere: still run, so the headless modes work and the GUI path can
# explain itself properly.
if [ -z "$CHOSEN" ]; then
    for candidate in $CANDIDATES; do
        if runs "$candidate" "$BASE_PROBE"; then
            CHOSEN="$candidate"
            break
        fi
    done
fi

if [ -z "$CHOSEN" ]; then
    cat >&2 <<'EOF'
dockmaster: no usable Python 3.9+ interpreter found.

Checked /usr/bin/python3 and every /usr/bin/python3.N present.

If you have one somewhere else:
    DOCKMASTER_PYTHON=/path/to/python3 dockmaster
EOF
    exit 1
fi

export PYTHONPATH="$ROOT${PYTHONPATH:+:$PYTHONPATH}"
exec "$CHOSEN" -m dockmaster "$@"
