#!/bin/sh
#
# NB: this should be part of extracttests.py!

# we expect input from extracttests.py (only 1 test per run!)
# output: directory ($testnum) with pe inputs from all nodes

usage() {
	cat<<EOF

usage: $0 [-t]

Fetch pe input files from all nodes which were created during
one CTS test run. The files are copied to directories named
after the node where they originated. The top level directory
is named after the test number.

-t: tar the files and remove directories

Examples:

	python /usr/local/share/heartbeat/cts/extracttests.py /var/log/ha-debug 122 | $0
	python /usr/local/share/heartbeat/cts/extracttests.py /var/log/ha-debug 122 | tee 122.ha-debug | $0

NB: Files are copied using ssh as root. In case you use different
user for ssh run the program like this:

	SSH_USER=myuser $0

EOF
	exit
}

args=`getopt ht $*`
[ $? -ne 0 ] && usage

MKTAR=""
while [ x"$1" != x ]; do
	case "$1" in
		-h) usage;;
		-t) MKTAR=1;;
		--) break;;
		*) usage;;
	esac
	shift 1
done

. /etc/ha.d/shellfuncs


: ${SSH_USER="root"}
BEGINSTAMP=.begin.pe-inputs.$$
ENDSTAMP=.end.pe-inputs.$$

#
# parse input from extracttests.py
# try to find:
# - testnumber
# - nodes
# - begin and end timestamps
#
eval `awk '
BEGIN{t=0}
/CTS: \*/ {sub(":","",$(NF-1)); nodes[$(NF-1)]=1; }
/CTS: Running test/ {
	if( t==0 ) {
		gsub("[^0-9]","",$NF);
		testnum=$NF;
	}
	stamp[t++]=$1" "$2" "$3;
}
END {
	printf("nodes=\"");
	for(n in nodes)
		printf("%s ",n);
	printf("\"\n");
	printf("starttime=\"%s\"\n",stamp[0]);
	printf("endtime=\"%s\"\n",stamp[1]);
	printf("testnum=%d\n",testnum);
}
'`
test -z "$testnum" -o $testnum -lt 0 && {
	echo "sorry, could not get the test number"
	exit
}
test "$nodes" || {
	echo "sorry, could not get node names"
	exit
}
test "$starttime" -a "$endtime" || {
	echo "sorry, could not get all timestamps"
	exit
}

touch -d "$starttime" $BEGINSTAMP &&
	touch -d "$endtime" $ENDSTAMP || {
	echo "could not touch files; you probably need gnu touch(1)"
	exit
}

trap '
	rm -f $BEGINSTAMP $ENDSTAMP
	for n in $nodes; do
		ssh $SSH_USER@$n rm -f /tmp/$BEGINSTAMP /tmp/$ENDSTAMP 
	done
' EXIT

copystamps() {
	tar cf - $BEGINSTAMP $ENDSTAMP |
		ssh $SSH_USER@$n 'cd /tmp && tar xf -'
}
list_peinputs() {
	ssh $SSH_USER@$n ". /etc/ha.d/shellfuncs && cd \$HA_VARLIB && find pengine \
		-type f -newer /tmp/$BEGINSTAMP ! -newer /tmp/$ENDSTAMP"
}
tar_peinputs() {
	ssh $SSH_USER@$n ". /etc/ha.d/shellfuncs && cd \$HA_VARLIB && tar -cf - $*"
}

for n in $nodes; do
	copystamps
	flist=`list_peinputs`
	if [ "$flist" ]; then
		mkdir -p $testnum/$n
		tar_peinputs "`echo $flist`" | (cd $testnum/$n && tar xf -)
	fi
done

if [ "$MKTAR" ]; then
	if tar -cf $testnum-peinputs.tar $testnum
	then
		rm -rf $testnum
	else
		echo "failed to create $testnum-peinputs.tar.gz"
	fi
fi
