#!/bin/bash
# pymufem — launch a μfem case under MPI.
#
# Resolves libmufem (which ships mpiexec and the runtime libs) at run time so
# the script works under any Python minor version and any venv layout.

set -e

# pymufem lives in <env>/bin/. The sibling python interpreter is what we use
# to locate libmufem inside this env's site-packages.
BIN_DIR=$(dirname "$(realpath "$0")")
PYTHON=$BIN_DIR/python
[ -x "$PYTHON" ] || PYTHON=$BIN_DIR/python3
[ -x "$PYTHON" ] || { echo "pymufem: no python interpreter next to $0" >&2; exit 1; }

LIBMUFEM_DIR=$("$PYTHON" -c "import libmufem, os; print(os.path.dirname(libmufem.__file__))" 2>/dev/null) || {
    echo "pymufem: failed to import libmufem; install it via 'pip install libmufem'" >&2
    exit 1
}

export LD_LIBRARY_PATH="$LIBMUFEM_DIR/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export OPAL_PREFIX="$LIBMUFEM_DIR"

MPIEXEC=$LIBMUFEM_DIR/bin/mpiexec
[ -x "$MPIEXEC" ] || { echo "pymufem: $MPIEXEC missing or not executable" >&2; exit 1; }

if [[ $1 =~ ^[0-9]+$ ]]; then
    "$MPIEXEC" --allow-run-as-root -n "$1" "$PYTHON" "${@:2}"
else
    "$MPIEXEC" --allow-run-as-root "$PYTHON" "$@"
fi
