#!/bin/sh

tmp=/var/tmp/TopicCheck.$$
trap 'rm -fr "$tmp" "$tmp."*' 0 1 2 3 15

usage () {
	echo >&2 "usage: $0 [--with <base>] [--stdin | <topics>...]"
}

stdin= with=
while case "$1" in -*) ;; *) break; esac
do
	case "$1" in
	--stdin)
		stdin=stdin ;;
	--with)
		with="${2?<base>}"
		shift ;;
	*)
		usage
		exit 1 ;;
	esac
	shift
done

case "$#,$stdin" in
0,)
	stdin=stdin ;;
esac

section () {
	printf >&3 "\033]0;%s %s\007" "$*"
	printf >&3 "# %s %s\n" "$*"
	printf >&2 "\n\n\n\n##### %s %s\n\n\n\n" "$*"
}

git checkout --quiet --detach

logbase=./+log/$$
mkdir -p "$logbase"

exec 3>&2

onetopic () {
	topic="$1" rest="$2"
	label=${rest:-$topic}
	log="$logbase/$(echo "$topic" | tr '/' '-')"
	exec >"$log" 2>&1

	if test -n "$with"
	then
		git reset --hard "$with" &&
		git merge --quiet "$topic"
	else
		git reset --hard "$topic"
	fi || {
		echo >&2 "cannot prepare $label"
		return
	}

	failed=

	section "$label - leaks" &&
	(
		export SANITIZE=leak GIT_TEST_PASSING_SANITIZE_LEAK=true &&
		Meta/Make -j32  CC=clang test
		st=$?
		Meta/Make -j32  CC=clang  >/dev/null 2>&1 distclean
		exit $st
	) || failed="leaks"

	section "$label - sha256" &&
	(
		export GIT_TEST_DEFAULT_HASH=sha256 &&
		Meta/Make -j32 test
		st=$?
		Meta/Make >/dev/null 2>&1 distclean
		exit $st
	) || failed="$failed${failed:+" "}sha256"

	section "$label - test" &&
	(
		export GIT_TEST_LONG=YesPlease &&
		Meta/Make -j32 test
		st=$?
		Meta/Make >/dev/null 2>&1 distclean
		exit $st
	) || failed="$failed${failed:+" "}test"

	section "$label - breaking" &&
	(
		Meta/Make $jobs WITH_BREAKING_CHANGES=YesPlease $T test
		st=$?
		Meta/Make WITH_BREAKING_CHANGES=YesPlease >/dev/null 2>&1 distclean
		exit $st
	) || failed="$failed${failed:+" "}breaking"

	if test "$failed" = ""
	then
		rm -f "$log"
	else
		echo >&3 "failed ($failed) $label"
		echo >&2 "failed ($failed) $label"
	fi
}

if test "$stdin" = stdin
then
	while read topic
	do
		echo $(git rev-parse "$topic") "$topic"
	done
else
	for topic
	do
		echo $(git rev-parse "$topic") "$topic"
	done
fi >"$tmp".lst

while read oid topic
do
	onetopic "$oid" "$topic"
done <"$tmp".lst

rmdir 2>/dev/null "$logbase" || :
