#!/bin/sh
# This is autotest gathering tool, collecting game result info from
# all clients and putting it in single place (which is completely
# wiped otherwise).

. ./autotest-lib

mkdir -p "r/"
rm -f r/*

# First, gather pairing data:

for dir in c/*/*/; do
	pairing="${dir%/}"; pairing="${pairing#c/*/}"
	datfile="r/$pairing.dat"

	if [ ! -s "$datfile" ]; then
		# Common datfile header, required for twogtp -analyze
		{
		echo "#"
		echo -e "#GAME\tRES_B\tRES_W\tRES_R\tALT\tDUP\tLEN\tTIME_B\tTIME_W\tCPU_B\tCPU_W\tERR\tERR_MSG"
		} >"$datfile"
		num=0
	else
		lastgame="$(tail -n 1 "$datfile")"
		num="$((${lastgame%%	*} + 1))"
	fi
	# We cannot simply concatenate all the datfiles because
	# twogtp -analyze is pedantic about the games numbering;
	# we need to renumber the games to a single sequence.
	while read orignum line; do
		echo -e "$num\t$line"
		num=$((num+1))
	done <"$dir/game.dat" >>"$datfile"
done


# Next, fill per-pairing metadata:

for datfile in r/*.dat; do
	pairing="${datfile%.dat}"; pairing="${pairing#r/}"

	# Look at last change in pairing:
	stat -c %Z "$(ls --sort=time c/*/"$pairing"/* | head -n 1)" >"r/$pairing.beacon"

	# Check pairing for errors:
	tail -n +3 "$datfile" | cut -f 12 | { grep -c -vF 0 >"r/$pairing.error" || :; }
done
