#!/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 "  -o PATH     output directory"
	echo "  -t TITLE    title of the report"
}

image_links()
{
	find "${INDIR}" -name "index-stat-$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()
{
	while IFS= read -r INDEX; do
		echo ".. image:: ../index-stat-${INDEX}-${METRIC}.png"
		echo "   :target: ../index-stat-${INDEX}-${METRIC}.png"
		echo "   :width: 100%"
		echo ""
	done < "$INDEXLISTFILE"
}

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

while getopts "hi:o:t:" opt; do
	case $opt in
	i)
		INDEXLISTFILE=$OPTARG
		;;
	h)
		usage
		exit 1
		;;
	o)
		# Overloading this flag, the charts must also be in this directory.
		INDIR=$OPTARG
		;;
	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.

while IFS= read -r INDEX; do
	OUTDIR="${INDIR}/${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 < "$INDEXLISTFILE"

# Create report showing all indexes for a metric.

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

for METRIC in $INDEXMETRICS; do
	OUTDIR="${INDIR}/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
