#!/bin/sh

set -e

# calculate number of parallel jobs by assuming 4GB RAM and 1 CPU per job
RAM_PER_JOB="4"

CPU="$(nproc)"
RAM="$(free --giga | awk '/^Mem:/ { print $2 }')"

if [ "${RAM}" -ge "${RAM_PER_JOB}" ]
then
	# system has enough RAM for more than one job

	if [ "${RAM}" -ge "$(( ${CPU} * ${RAM_PER_JOB} ))" ]
	then
		# system has more RAM than CPU
		JOBS="${CPU}"
	else
		# system has more CPU than RAM
		JOBS="$(( ${RAM} / ${RAM_PER_JOB} ))"
	fi
else
	# system has not enough RAM for more than one job
	JOBS="1"
fi

case "${1}" in
	--info)
		echo "# info: building in parallel with ${JOBS} jobs on ${CPU} CPUs and ${RAM}GB RAM"
		;;

	*)
		echo "--max-parallel=${JOBS}"
		;;
esac
