#!/bin/sh
#
# Run the automated tests for the project.

set -eu

die() {
	echo "$@" >&1
	exit 1
}

hideok=chronic
image=''

if ! command -v chronic >/dev/null; then
	hideok=
fi

while [ "$#" -gt 0 ]; do
	case "$1" in
	-v | --verbose)
		hideok=
		shift
		;;
	-i | --image)
		shift
		if [ "$#" = 0 ]; then
			die "--image MUST have an argument"
		fi
		image="$1"
		shift
		;;
	*)
		break
		;;
	esac
done

require_cmd() {
	if ! command -v "$1" >/dev/null; then
		echo "Need to have $1 installed, but can't find it" 1>&2
		return 1
	fi
}

got_cargo_cmd() {
	cargo "$1" --help >/dev/null
}

require_cmd rustc
require_cmd cc
require_cmd cargo
require_cmd python3
require_cmd subplot

$hideok cargo --version
$hideok rustc --version

got_cargo_cmd clippy && cargo clippy --all-targets -q -- -D warnings
$hideok cargo build --all-targets --target x86_64-unknown-linux-musl
got_cargo_cmd fmt && $hideok cargo fmt -- --check
$hideok cargo test

subplot docgen ambient-driver.subplot -o ambient-driver.html

bindir="$(mktemp -d)"
trap 'rm -rf "$bindir"' EXIT
cargo install --bins --path=. --target x86_64-unknown-linux-musl \
	--root="$bindir" --target=x86_64-unknown-linux-musl

subplot codegen ambient-driver.subplot -o test.py
rm -f test.log
$hideok python3 test.py --log test.log --env "BINDIR=$bindir/bin" --env "IMAGE=$image" "$@"

echo "Everything seems to be in order."
