#!/bin/bash
# Run `make <targets>` for a ChimeraX bundle inside the matching build
# container. Run it from any bundle's source directory (one with a Makefile
# that drives `devel build` / `devel install`).
#
#   cxmake [daily|release] <make targets...>
#
# The channel argument drives BOTH the image selection and the Makefile's
# RELEASE switch, so there is a single source of truth (no RELEASE baked into
# the image environment).
#
#   cxmake daily clean app-install
#   cxmake release app-install
#   cxmake app-install            # defaults to daily
set -euo pipefail

: "${CHIMERAX_BUILDENV:=${XDG_CACHE_HOME:-$HOME/.cache}/chimerax-buildenv}"

CHANNEL=daily
case "${1:-}" in
    daily|release) CHANNEL="$1"; shift ;;
esac

# One combined image holds both channels; the Makefile picks the executable
# (`chimerax` vs `chimerax-daily`) from the RELEASE switch below.
IMG="$CHIMERAX_BUILDENV/chimerax.sif"
if [[ ! -e "$IMG" ]]; then
    echo "cxmake: missing image $IMG" >&2
    echo "        build it with:  refresh-chimerax /path/to/[ucsf-]chimerax[-daily]*.rpm" >&2
    exit 1
fi

# Only DEFINE RELEASE for the release channel; the Makefile keys on ifdef.
ENV_ARGS=()
EXE=chimerax-daily
[[ "$CHANNEL" == release ]] && { ENV_ARGS=(--env RELEASE=1); EXE=chimerax; }

echo "cxmake: building in Singularity container [$CHANNEL -> $EXE] using $IMG" >&2

exec singularity exec "${ENV_ARGS[@]}" \
    --bind "$PWD" --pwd "$PWD" "$IMG" make "$@"
