#!/bin/sh
# Beegait runner launcher (Debian package, card 180 MV2-RUNNER-DEB-LINUX).
# A PER-USER venv under $XDG_DATA_HOME/maistro-runner, built OFFLINE from the wheel this
# package ships (never pip from the network) and refreshed when the package's version
# changes (apt upgrade). Root never owns the runner's Python: the engine's self-update
# lane (pip into this venv) needs no privilege, and several users share one package.
set -e
SHARE=/usr/share/maistro-runner
DATA="${XDG_DATA_HOME:-$HOME/.local/share}/maistro-runner"
VENV="$DATA/venv"
# card MV2-SEC-ENGINE-WHEEL-COMPILED-MAC-LINUX: the package ships one COMPILED wheel per CPython minor
# beside the pure one; pip picks by tag. The box's python tag joins the compare, so a distro
# upgrade (3.10 -> 3.12) rebuilds the venv with the right wheel instead of keeping a cp310 .so
# under a 3.12 interpreter; a venv bound to a gone interpreter is rebuilt from scratch.
tag=$(python3 -c 'import sys,sysconfig;print(sys.implementation.cache_tag+"-"+sysconfig.get_platform().replace("-","_").replace(".","_"))' 2>/dev/null || echo unknown)
want="$(cat "$SHARE/version" 2>/dev/null || echo unknown) $tag"
have=$(cat "$VENV/package-version" 2>/dev/null || true)
if [ ! -x "$VENV/bin/python3" ] || [ "$want" != "$have" ]; then
    mkdir -p "$DATA"
    # one builder at a time (two terminals / logins racing the first run)
    n=0
    while ! mkdir "$DATA/.venv-lock" 2>/dev/null; do
        n=$((n + 1))
        if [ "$n" -gt 180 ]; then rm -rf "$DATA/.venv-lock"; break; fi
        sleep 1
    done
    trap 'rmdir "$DATA/.venv-lock" 2>/dev/null' EXIT INT TERM
    have=$(cat "$VENV/package-version" 2>/dev/null || true)
    if [ ! -x "$VENV/bin/python3" ] || [ "$want" != "$have" ]; then
        if [ ! -x "$VENV/bin/python3" ] || [ "${have#* }" != "$tag" ]; then
            rm -rf "$VENV"
            python3 -m venv --system-site-packages "$VENV"   # python3-yaml comes from the distro
        fi
        "$VENV/bin/python3" -m pip install --quiet --disable-pip-version-check --no-index \
            --find-links "$SHARE/dist" --upgrade beegait-engine
        cp "$SHARE/package.json" "$VENV/package.json"
        printf '%s\n' "$want" > "$VENV/package-version"
        picked=$("$VENV/bin/python3" -c 'import importlib.metadata as m;print([l.split(":",1)[1].strip() for l in [x for x in m.distributions() if (x.metadata["Name"] or "").lower() in ("beegait-engine","maistro-engine")][0].read_text("WHEEL").splitlines() if l.startswith("Tag:")][0])' 2>/dev/null || echo unknown)
        echo "maistro-runner: engine ${want% *} installed into $VENV from the $picked wheel (this python: $tag)" >&2
    fi
    rmdir "$DATA/.venv-lock" 2>/dev/null || true
    trap - EXIT INT TERM
fi
exec "$VENV/bin/python3" -m maistro "$@"
