#!/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 Tools Authors
#

usage()
{
	echo "$(basename "$0") is the PostgreSQL index statistics rst report generator"
	echo ""
	echo "Usage:"
	echo "  $(basename "$0") [OPTION]"
	echo ""
	echo "Options:"
	echo "  -i FILE     table list file"
	echo "  -t TITLE    title of the report"
}

image_links()
{
	find "${INDIR}" -name "pgsql-${INDEX}-*.png" | while IFS= read -r CHART
	do
		CHART=$(basename "$CHART")
		echo ".. image:: ../${CHART}"
		echo "   :target: ../${CHART}"
		echo "   :width: 100%"
		echo ""
	done
}

image_links_by_metric()
{
	grep ^public "$INDEXLISTFILE" | while IFS= read -r INDEX; do
		echo ".. image:: ../../index/pgsql-${INDEX}-${METRIC}.png"
		echo "   :target: ../../index/pgsql-${INDEX}-${METRIC}.png"
		echo "   :width: 100%"
		echo ""
	done
}

error() {
	echo "ERROR: $*"
	exit 1
}

while getopts "hi:t:" opt; do
	case $opt in
	i)
		INDEXLISTFILE=$OPTARG
		INDIR="$(dirname "${INDEXLISTFILE}")"
		;;
	h)
		usage
		exit 1
		;;
	t)
		TITLE=$OPTARG
		;;
	\?)
		usage
		exit 1
		;;
	esac
done

if [ "$INDEXLISTFILE" = "" ]; then
	error "index list file was not specified with -i"
fi

if [ ! -f "$INDEXLISTFILE" ]; then
	error "index list file $INDEXLISTFILE not found"
fi

# Create report listing stats for an index.

grep ^public "$INDEXLISTFILE" | grep -v "\.pg_catalog\." | \
		while IFS= read -r INDEX; do
	OUTDIR="${INDIR}/index/${INDEX}"
	mkdir -p "$OUTDIR"
	if [ ! -d "$OUTDIR" ]; then
		error "could not create directory $OUTDIR"
	fi

	INDEXCHARTFILE="${OUTDIR}/index.rst"
	cat > "$INDEXCHARTFILE" << __EOF__
================================================================================
$TITLE $INDEX Index Charts
================================================================================

$(image_links)
__EOF__
done

# Create report showing all indexes for a metric.

INDEXMETRICS=$( (cd "$INDIR/index" && ls ./*.png) 2> /dev/null | \
		sed -e "s/^.\/pgsql-*.*.*-//" | sed -e "s/.png$//" | sort | uniq)

for METRIC in $INDEXMETRICS; do
	OUTDIR="${INDIR}/index-stat/i_${METRIC}"
	mkdir -p "$OUTDIR"
	if [ ! -d "$OUTDIR" ]; then
		error "ERROR: could not create directory $OUTDIR"
	fi

	METRICCHARTFILE="${OUTDIR}/index.rst"
	cat > "$METRICCHARTFILE" << __EOF__
================================================================================
$TITLE Index $METRIC Charts
================================================================================

$(image_links_by_metric)
__EOF__
done
