#!/bin/sh
# Copyright 2024 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: GPL-3

TOOL="$1"


FAILCOUNT=0

fail() {
	FAILCOUNT=$((FAILCOUNT + 1))
	echo "command: $COMMAND"
	echo "output: $RES"
	echo "error: $*"
	echo
}

run() {
	COMMAND="$TOOL $*"
	if ! RES=$("$TOOL" "$@"); then
		fail "exit code $?"
		RES=
	fi
}

assert_range() {
	if test "$RES" -lt "$1"; then
		fail "expected >= $1"
	fi
	if test -n "$2" && test "$RES" -gt "$2"; then
		fail "expected <= $2"
	fi
}

assert_equal() {
	if test "$RES" != "$1"; then
		fail "expected $1"
	fi
}

run
assert_range 1 ""

unset CMAKE_BUILD_PARALLEL_LEVEL
unset DEB_BUILD_OPTIONS
unset RPM_BUILD_NCPUS

run --detect=python
assert_range 1 ""

run --detect=cores
assert_range 1 ""

run --detect=3
assert_equal 3

run --detect=9999 --max=5
assert_equal 5

run --detect=2 --min=5
assert_equal 5

# Implied assumption: We have less than 900TiB RAM.
run --detect=9999 --require-mem=99g
assert_range 1 9998

DEB_BUILD_OPTIONS="spam parallel=42 beacon" run
assert_equal 42

RPM_BUILD_NCPUS=43 run
assert_equal 43

if test "$FAILCOUNT" -gt 0; then
	echo "encountered $FAILCOUNT failures"
	exit 1
fi
