#!/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()
{
	echo "`basename $0` is the DBT-2 PostgreSQL Report Generator"
	echo ""
	echo "Usage:"
	echo "  `basename $0` [OPTIONS]"
	echo ""
	echo "General options:"
	echo "  -i PATH          results directory"
}

create_stat_page()
{
	NAME=$1
	TAG=$2

	OUTDIR="${PIDSTATDIR}/$TAG"
	mkdir -p $OUTDIR

	cat > ${OUTDIR}/index.rst << __EOF__
================================================================================
Database Test 2 pidstat $TAG Charts
================================================================================

$(show_images $NAME $TAG)
__EOF__
}

links_index_metrics()
{
	NAME=$1

	INDEXMETRICS=$( (cd "${INDIR}/db/${NAME}/dbstat/index" && \
			find . -name "*.png") | sed -e "s/.\/pgsql-*.*.*-//" | \
			sed -e "s/.png$//" | sort | uniq)

	for METRIC in $INDEXMETRICS; do
		echo -n "\`$METRIC <db/${NAME}/dbstat/index-stat/i_$METRIC/>\`__ "
	done
}

links_indexes()
{
	NAME=$1

	grep ^public\. "${INDIR}/db/${NAME}/dbstat/index-list.txt" | \
			grep -v "\.pg_catalog\." | while IFS= read -r INDEX; do
		printf "\`%s <db/%s/dbstat/index/%s/>\`__ " "${INDEX}" "${NAME}" \
				"${INDEX}"
	done
}

links_table_metrics()
{
	NAME=$1

	TABLEMETRICS=$( (cd "${INDIR}/db/${NAME}/dbstat/table" && \
			find . -name "*.png") | sed -e "s/^.\/pgsql-*.*-//" | \
			sed -e "s/.png$//" | sort | uniq)

	for METRIC in $TABLEMETRICS; do
		echo -n "\`$METRIC <db/${NAME}/dbstat/table-stat/t_${METRIC}/>\`__ "
	done
}

links_tables()
{
	NAME=$1

	grep ^public\. "${INDIR}/db/${NAME}/dbstat/table-list.txt" | \
			while IFS= read -r TABLE; do
		printf "\`%s <db/%s/dbstat/table/%s/>\`__ " "${TABLE}" "${NAME}" \
				"${TABLE}"
	done
}

list_processes()
{
	NAME=$1

	if [ ! -f "$PIDSTATCSV" ]; then
		return
	fi

	for T in autovacuum bgwriter checkpointer logger logical statscollector \
			walwriter; do
		create_stat_page $SNAME $T
		echo "* \`$T <db/${SNAME}/sysstat/${T}/>\`__"
	done
	echo ""
}

make_list()
{
	# The reporting of database system is naively based on whether the
	# dbstat diretory was created by ts-pgsql-stat script.
	find "${INDIR}/db" -type d -name dbstat 2> /dev/null | \
			while IFS= read -r STATDIR; do
		SNAME="$(basename "$(dirname "${STATDIR}")")"

		PIDSTATCSV="${INDIR}/db/${SNAME}/sysstat/pidstat.csv"
		PIDSTATDIR=$(dirname $PIDSTATCSV)

		# Create additional HTML pages for the database charts.

		which dbt-pgsql-generate-db-report > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			dbt-pgsql-generate-db-report -t "Database Test 2" -d dbt2 \
					-i "${INDIR}/db/${SNAME}/dbstat"
		fi
		which dbt-pgsql-generate-table-report > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			dbt-pgsql-generate-table-report -t "Database Test 2" \
					-i "${INDIR}/db/${SNAME}/dbstat/table-list.txt"
		fi
		which dbt-pgsql-generate-index-report > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			dbt-pgsql-generate-index-report -t "Database Test 2" \
					-i "${INDIR}/db/${SNAME}/dbstat/index-list.txt"
		fi

		cat << __EOF__
$SNAME
--------------------------------------------------------------------------------

* \`Database Parameters <db/${SNAME}/dbstat/params.csv>\`__
* \`Query plans <db/${SNAME}/plan0.txt>\`__

.. list-table::

   * - Database Stats Charts
     - \`dbt2 <db/${SNAME}/dbstat/db/dbt2>\`__
   * - Database Table Stats Charts:
     - $(links_tables $SNAME)
   * - Database Index Stats Charts:
     - $(links_indexes $SNAME)
   * - Database Tables by Metric:
     - $(links_table_metrics $SNAME)
   * - Database Indexs by Metric:
     - $(links_index_metrics $SNAME)

Per Process Statistics
----------------------

$(list_processes $SNAME)

__EOF__
	done
}

show_images()
{
	NAME=$1
	TAG=$2

	TAGPIDS=$(grep "${TAG}" "${PIDSTATDIR}/pidstat-index.txt" | \
			cut -d " " -f 1)
	for P in ${TAGPIDS}; do
		CHARTS=$(find "${PIDSTATDIR}" -type f -name "pidstat-${P}-*.png" | \
				sort)
		for CHART in $CHARTS; do
			BCHART=$(basename "${CHART}")
			echo ".. image:: ../pidstat/${BCHART}"
			echo "   :target: ../pidstat/${BCHART}"
			echo "   :width: 100%"
			echo ""
		done
	done
}

while getopts "hi:" opt; do
	case $opt in
	h)
		usage
		exit 1
		;;
	i)
		INDIR="$OPTARG"
		;;
	\?)
		exit 1
		;;
	esac
done

# shellcheck disable=SC2044
for DBDIR in $(find "${INDIR}" -type d -name dbstat); do
	ts plot-pgsql -d dbt2 -i "${DBDIR}" &
done
wait

DBNAME=$(grep "Database Name" ${INDIR}/readme.txt | cut -d " " -f 3)
if [ "x${DBNAME}" = "x" ]; then
	echo "ERROR: Could not determine what the database name used from results"
	exit 1
fi

cat << __EOF__
PostgreSQL Report
=================

$(make_list)
__EOF__
