#!/usr/bin/env bash

set -euo pipefail

apptainer_bin=$(command -v apptainer) || {
    echo "ERROR: DAYOA APPTAINER: apptainer is not available on PATH." >&2
    exit 127
}

if mountpoint -q -- /scratch; then
    if [[ -n "${APPTAINER_BINDPATH:-}" ]]; then
        export APPTAINER_BINDPATH="${APPTAINER_BINDPATH},/scratch:/scratch"
    else
        export APPTAINER_BINDPATH="/scratch:/scratch"
    fi
else
    echo "WARNING: DAYOA APPTAINER: /scratch is not a mounted host filesystem; omitting the optional /scratch bind." >&2
fi

# The configured path is inherited from the headnode, but /tmp is node-local.
# Create that exact configured build directory on the node executing Apptainer.
: "${APPTAINER_TMPDIR:?ERROR: DAYOA APPTAINER: APPTAINER_TMPDIR is not configured.}"
[[ "$APPTAINER_TMPDIR" = /* ]] || {
    echo "ERROR: DAYOA APPTAINER: APPTAINER_TMPDIR must be absolute." >&2
    exit 2
}
mkdir -p -- "$APPTAINER_TMPDIR"

exec "$apptainer_bin" "$@"
