#!/bin/sh

#
# This file is released under the terms of the Artistic License.
# Please see the file LICENSE, included in this package, for details.
#
# Copyright The DBT-2 Authors
#

usage()
{
	cat << EOF
$(basename "${0}") is the Database Test 2 (DBT-2) report generator

Usage:
  $(basename "${0}") [OPTIONS] DIRECTORY

General options:
  --html         generate HTML report
  -V, --version  output version information, then exit
  -?, --help     show this help, then exit

Database Test 2 (DBT-2) project page: https://github.com/osdldbt/dbt2
EOF
}
if [ "$DBT2LANG" = "" ]; then
	# Ordered preference of which language usually runs faster.
	if which "sqlite3" > /dev/null 2>&1; then
		DBT2LANG="sqlite3"
	elif which "R" > /dev/null 2>&1; then
		DBT2LANG="R"
	else
		echo "ERROR: 'sqlite3' nor 'R' not detected for post processing"
		exit 1
	fi
else
	if ! which "$DBT2LANG" > /dev/null 2>&1; then
		echo "ERROR: $DBT2LANG not detected, set to 'sqlite3' or 'R', or unset"
		echo "to let the script autodetect"
		exit 1
	fi
fi

HTML=0

# Custom argument handling for hopefully most portability.
while [ "${#}" -gt 0 ] ; do
	case "${1}" in
	(--html)
		HTML=1
		;;
	(-V | --version)
		echo "$(basename "${0}") v0.61.7"
		exit 0
		;;
	(-\? | --help)
		usage
		exit 0
		;;
	(--* | -*)
		echo "$(basename "${0}"): invalid option -- '${1}'"
		echo "try \"$(basename "${0}") --help\" for more information."
		exit 1
		;;
	(*)
		break
		;;
	esac
	shift
done

DIRECTORY="${1}"

if [ "$DBT2LANG" = "R" ]; then
	PPEXT="r"
elif [ "$DBT2LANG" = "sqlite3" ]; then
	PPEXT="sqlite3"
fi

PPSCRIPT="dbt2-post-process.${PPEXT}"

if ! which "$PPSCRIPT" > /dev/null 2>&1; then
		echo "ERROR: $PPSCRIPT not found in PATH"
		exit 1
fi

if [ ${HTML} -eq 1 ]; then
	dbt2 generate-report -i "${DIRECTORY}"
	cat "${DIRECTORY}/summary.rst"
else
	find "${DIRECTORY}/driver" -name 'mix*.log' -print0 | \
			xargs -0 "${PPSCRIPT}"
fi
