#!/bin/bash
# Build the LCD toolchain image (rockylinux:9 + stock GCC 11). Run rarely --
# only when ChimeraX bumps its build environment (check toolchain.def against
# <ChimeraX>/prereqs/linux_buildenv/rhel-9.def). ChimeraX updates do NOT need
# this; use refresh-chimerax for those.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
: "${CHIMERAX_BUILDENV:=${XDG_CACHE_HOME:-$HOME/.cache}/chimerax-buildenv}"
TOOLCHAIN_SIF="$CHIMERAX_BUILDENV/toolchain-el9.sif"

mkdir -p "$CHIMERAX_BUILDENV"

if [[ -e "$TOOLCHAIN_SIF" && "${1:-}" != "-f" ]]; then
    echo "Toolchain already exists: $TOOLCHAIN_SIF"
    echo "Pass -f to rebuild from scratch."
    exit 0
fi

echo "Building $TOOLCHAIN_SIF from $HERE/toolchain.def ..."
singularity build --fakeroot --force "$TOOLCHAIN_SIF" "$HERE/toolchain.def"
echo "Done: $TOOLCHAIN_SIF"
echo "Verifying compiler (expect gcc 11.x for the glibc-2.34 / GLIBCXX_3.4.29 contract):"
singularity exec "$TOOLCHAIN_SIF" gcc --version | head -1
