#!/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 "  -t TITLE    title of the report"
}

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

image_links()
{
	find "${INDIR}" -name "pgsql-${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()
{
	grep ^public "$TABLELISTFILE" | while IFS= read -r TABLE; do
		echo ".. image:: ../../table/pgsql-${TABLE}-${METRIC}.png"
		echo "   :target: ../../table/pgsql-${TABLE}-${METRIC}.png"
		echo "   :width: 100%"
		echo ""
	done
}

while getopts "hi:t:" opt; do
	case $opt in
	i)
		TABLELISTFILE=$OPTARG
		INDIR="$(dirname "${TABLELISTFILE}")"
		;;
	h)
		usage
		exit 1
		;;
	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 statistics.

grep ^public "$TABLELISTFILE" | while IFS= read -r TABLE; do
	OUTDIR="${INDIR}/table/${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

# Create reports by table metrics.

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

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