#!/bin/bash
set -euo pipefail

if [[ $# -lt 1 ]]; then
    echo "Usage: smartsim-openfoam-exec <solver> [solver arguments ...]" >&2
    exit 2
fi

if [[ -z "${SMARTSIM_ENV_LOADER:-}" ]]; then
    echo "ERROR: SMARTSIM_ENV_LOADER is not set." >&2
    exit 1
fi

if [[ ! -f "$SMARTSIM_ENV_LOADER" ]]; then
    echo "ERROR: SmartSim environment loader was not found:" >&2
    echo "       $SMARTSIM_ENV_LOADER" >&2
    exit 1
fi

export SMARTSIM_ENV_QUIET=1
source "$SMARTSIM_ENV_LOADER"
unset SMARTSIM_ENV_QUIET

solver="$1"
shift

solver_path="$FOAM_APPBIN/$solver"

if [[ ! -x "$solver_path" ]]; then
    solver_path="$FOAM_USER_APPBIN/$solver"
fi

if [[ ! -x "$solver_path" ]]; then
    echo "ERROR: OpenFOAM executable was not found:" >&2
    echo "       Solver:           $solver" >&2
    echo "       FOAM_APPBIN:      $FOAM_APPBIN" >&2
    echo "       FOAM_USER_APPBIN: $FOAM_USER_APPBIN" >&2
    exit 127
fi

exec "$solver_path" "$@"
