#!/bin/sh
# Parse r2r JSON output to inspect test results
# The r2r.json file is generated by `r2r -j` and can be taken from CI
# Useful to find out which tests are broken, fixed, failed, or slow

R2R_JSON="${R2R_JSON:-/tmp/r2r.json}"

if [ ! -f "$R2R_JSON" ]; then
	echo "Cannot find $R2R_JSON (set R2R_JSON env to override)" >&2
	exit 1
fi

show_help() {
	echo "Usage: $0 [-h] [-b] [-x] [-f] [-o] [-s] [-S] [-t] [-n name]"
	echo "  -b       list broken tests (marked broken, still failing)"
	echo "  -x       list fixed tests (marked broken, but passing)"
	echo "  -f       list failed tests (expected pass, but failing)"
	echo "  -o       list ok (passing) tests"
	echo "  -s       list skipped tests"
	echo "  -S       summary counts"
	echo "  -t       sort by time elapsed (slowest last)"
	echo "  -n name  filter by test name substring"
	echo "  -h       show this help"
	echo ""
	echo "  No arguments: sort all tests by time elapsed"
	echo "  R2R_JSON env var overrides input file (default: /tmp/r2r.json)"
}

FILTER=""
NAME=""
SORT_TIME=0

if [ $# -eq 0 ]; then
	# default: sort by time
	jq -r 'sort_by(.time_elapsed) | .[] | "\(.time_elapsed)\t\(.result)\t\(.name // .cmd // .arch // .file // "?")"' < "$R2R_JSON"
	exit 0
fi

while getopts "hbxfosStn:" opt; do
	case "$opt" in
	b) FILTER="broken" ;;
	x) FILTER="fixed" ;;
	f) FILTER="failed" ;;
	o) FILTER="ok" ;;
	s) FILTER="skipped" ;;
	t) SORT_TIME=1 ;;
	n) NAME="$OPTARG" ;;
	S)
		echo "=== r2r test summary ==="
		jq -r '[group_by(.result) | .[] | {result: .[0].result, count: length}] | sort_by(.result) | .[] | "\(.result)\t\(.count)"' < "$R2R_JSON"
		TOTAL=$(jq 'length' < "$R2R_JSON")
		echo "---"
		echo "total	$TOTAL"
		exit 0
		;;
	h) show_help; exit 0 ;;
	*) show_help; exit 1 ;;
	esac
done

# Build jq filter
JQ='.'
if [ -n "$FILTER" ]; then
	JQ="$JQ | map(select(.result == \"$FILTER\"))"
fi
if [ -n "$NAME" ]; then
	JQ="$JQ | map(select((.name // .cmd // .arch // .file // \"\") | test(\"$NAME\"; \"i\")))"
fi
if [ "$SORT_TIME" = 1 ]; then
	JQ="$JQ | sort_by(.time_elapsed)"
fi
JQ="$JQ | .[] | \"\(.time_elapsed)\t\(.result)\t\(.name // .cmd // .arch // .file // \"?\")\""

jq -r "$JQ" < "$R2R_JSON"
