#!/bin/sh
#
# this script can be used by developers to compile for multiple
# variations efficiently without exhausting the machine for ram or
# cpu. it uses GNU make and it's builtin jobserver support, so might
# not work on other platforms than linux.
#
# stand in the git root and execute the script.
# then build with:
#   make -j$(nproc) -C build/multibuild/ all
# test with:
# make -j$(nproc) -C build/multibuild/ testall

set -eu

builddirbase=build/multibuild
mkdir -p $builddirbase

makefile=$builddirbase/Makefile
echo "#autogenerated by $0 at $(date --rfc-3339=s), do not edit" >$makefile
echo ".PHONY: all">>$makefile

echo ".PHONY: testall">>$makefile
echo "testall:">>$makefile

compilers="g++-12 g++-13 g++-14 clang++-19"
standards="17 20 23"
buildtypes="Release Debug"

for compiler in $compilers; do
    if ! which $compiler >/dev/null; then
	continue
    fi
    compilerbin=/usr/lib/ccache/$compiler
    if [ ! -x $compilerbin ]; then
	compilerbin=$compiler
    fi
    for buildtype in $buildtypes; do
	for standard in $standards; do
	    relbuilddir=$compiler-c++$standard-$buildtype
	    builddir=$builddirbase/$relbuilddir
	    if [ ! -d $builddir ]; then
		cmake -B $builddir -S . \
		      -DCMAKE_CXX_COMPILER=$compilerbin \
		      -DSIMDUTF_CXX_STANDARD=$standard \
		      -DCMAKE_BUILD_TYPE=$buildtype \
		      -DCMAKE_COMPILE_WARNING_AS_ERROR=On \
		      -DCMAKE_EXPORT_COMPILE_COMMANDS=On \
		      -DSIMDUTF_FAST_TESTS=On \
		      -DBUILD_SHARED_LIBS=On
	    fi
	    
	    echo "all: $relbuilddir/done" >> $makefile
	    echo ".PHONY: $relbuilddir/done" >> $makefile
	    echo "$relbuilddir/done:" >>  $makefile
	    echo "\t\$(MAKE) -C $relbuilddir && touch $relbuilddir/done" >> $makefile

	    echo "testall: $relbuilddir/tested" >> $makefile
	    echo ".PHONY: $relbuilddir/tested" >> $makefile
	    echo "$relbuilddir/tested:" >>  $makefile
	    echo "\t\$(MAKE) -C $relbuilddir test && touch $relbuilddir/tested" >> $makefile
	done
    done
done
