#!/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 table 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"
}

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

image_links()
{
	find "${INDIR}" -name "table-stat-$TABLE-*.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 TABLE; do
		echo ".. image:: ../table-stat-${TABLE}-${METRIC}.png"
		echo "   :target: ../table-stat-${TABLE}-${METRIC}.png"
		echo "   :width: 100%"
		echo ""
	done < "$TABLELISTFILE"
}

while getopts "hi:o:t:" opt; do
	case $opt in
	i)
		TABLELISTFILE=$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 [ "$TABLELISTFILE" = "" ]; then
	error "table list file was not specified with -i"
fi

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

# Create reports for table statisics.

while IFS= read -r TABLE; do
	OUTDIR="${INDIR}/${TABLE}"
	mkdir -p "$OUTDIR"
	if [ ! -d "$OUTDIR" ]; then
		error "could not create directory $OUTDIR"
	fi

	TABLECHARTFILE="${OUTDIR}/index.rst"
	cat > "$TABLECHARTFILE" << __EOF__
================================================================================
$TITLE $TABLE Table Charts
================================================================================

$(image_links)
__EOF__
done < "$TABLELISTFILE"

# Create reports by table metrics.

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

for METRIC in $TABLEMETRICS; do
	OUTDIR="${INDIR}/t_${METRIC}"
	mkdir -p "$OUTDIR"
	if [ ! -d "$OUTDIR" ]; then
		error "could not create directory $OUTDIR"
	fi

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

$(image_links_by_metric)
__EOF__
done
