#!/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 (C) 2022      Mark Wong
#

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()
{
	for CHART in `(cd $INDIR && ls -v index-stat-$INDEX-*.png) 2> /dev/null`; do
		echo ".. image:: ../$CHART"
		echo "   :target: ../$CHART"
		echo "   :width: 100%"
		echo ""
	done
}

image_links_by_metric()
{
	for INDEX in `cat $INDEXLISTFILE`; do
		echo ".. image:: ../index-stat-${INDEX}-${METRIC}.png"
		echo "   :target: ../index-stat-${INDEX}-${METRIC}.png"
		echo "   :width: 100%"
		echo ""
	done
}

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 [ "x$INDEXLISTFILE" = "x" ]; 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.

for INDEX in `cat $INDEXLISTFILE`; 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

# 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`

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
