#!/bin/sh
# sysaudit 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. sysaudit reports that as a finding; it does not
# quietly repair it, and it must still be able to start.
#
# Override the choice with SYSAUDIT_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")")

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

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

CHOSEN=""

# An explicit override always wins, and fails loudly rather than falling back.
if [ -n "${SYSAUDIT_PYTHON:-}" ]; then
    if works "$SYSAUDIT_PYTHON"; then
        CHOSEN="$SYSAUDIT_PYTHON"
    else
        echo "sysaudit: SYSAUDIT_PYTHON=$SYSAUDIT_PYTHON cannot import GTK4 + libadwaita." >&2
        exit 1
    fi
fi

if [ -z "$CHOSEN" ]; then
    for candidate in \
        /usr/bin/python3 \
        /usr/bin/python3.13 /usr/bin/python3.12 /usr/bin/python3.11 \
        /usr/bin/python3.10 /usr/bin/python3.9 \
        python3
    do
        if works "$candidate"; then
            CHOSEN="$candidate"
            break
        fi
    done
fi

if [ -z "$CHOSEN" ]; then
    cat >&2 <<'EOF'
sysaudit: no Python interpreter on this system can import GTK4 + libadwaita.

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

Most likely causes:

  1. PyGObject or the GTK4 typelibs are not installed:
         sudo apt install python3-gi gir1.2-gtk-4.0 gir1.2-adw-1

  2. python3 points at an interpreter with a different ABI than the distro's
     compiled extensions. Check with:
         update-alternatives --display python3
         ls /usr/lib/python3/dist-packages/gi/_gi*.so
     If the .so says cpython-310 but python3 is 3.11, that is the problem.
     Either run sysaudit against the matching interpreter:
         SYSAUDIT_PYTHON=/usr/bin/python3.10 sysaudit
     or restore the distro default:
         sudo update-alternatives --auto python3
EOF
    exit 1
fi

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