#!/bin/bash
set -euo pipefail

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

if [[ -n "${SMARTSIM_ENV_LOADER:-}" ]]; then
    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
fi

required_variables=(
    FOAM_APPBIN
    FOAM_USER_APPBIN
)

for variable_name in "${required_variables[@]}"; do
    if [[ -z "${!variable_name:-}" ]]; then
        echo "ERROR: OpenFOAM environment is incomplete." >&2
        echo "       Missing variable: $variable_name" >&2
        echo "       Activate OpenFOAM or set SMARTSIM_ENV_LOADER." >&2
        exit 1
    fi
done

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" "$@"
