#!/usr/bin/env bash

# Our custom diff tool which normalizes result and expected files before
# doing the actual diff. Rules for normalization are in normalize.sed. See
# the comments there for more information.
#
# We only normalize tests listed in normalized_tests.lst. We use the bare
# diff for other tests.
#
# Note that src/test/regress/Makefile adds this directory to $PATH so
# pg_regress uses this diff tool instead of the system diff tool.

file1="${@:(-2):1}"
file2="${@:(-1):1}"
# pg_regress passes the expected file as the first argument ($file1 above),
# and results file as the second argument ($file2 above). We take the base
# filename of the expected file as the test name. We can have multiple
# expected files for a single test with _0, _1, ... suffixes.
# So for the test name, we also strip the additional suffix.
test=$(basename $file1 .out | sed -E "s/_[0-9]+$//")
args=${@:1:$#-2}
BASEDIR=$(dirname "$0")

# whereis searches for standard unix places before $PATH. So select the first
# entry as the original diff tool.
DIFF=$(whereis diff | sed "s/diff://g" | awk '{print $1}')
if [ -z "$DIFF" ]
then
    DIFF=/usr/bin/diff
fi

if test -z "$VANILLATEST"
then
	sed -Ef $BASEDIR/normalize.sed < $file1 > $file1.modified
	sed -Ef $BASEDIR/normalize.sed < $file2 > $file2.modified
	$DIFF -w $args $file1.modified $file2.modified
	exitcode=$?
	rm -f $file1.modified $file2.modified
	exit $exitcode
else
	exec $DIFF -w $args $file1 $file2
fi

