#!/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 database statistics rst report generator"
	echo ""
	echo "Usage:"
	echo "  $(basename "$0") [OPTION]"
	echo ""
	echo "Options:"
	echo "  -d DBNAME   dbname to generate report about"
	echo "  -h          display this help and exit"
	echo "  -i PATH     path to input files"
	echo "  -t TITLE    title of the report"
}

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

image_links()
{
	for CHART in "${INDIR}"/db/*.png; do
		[ -f "$CHART" ] || continue
		CHART="$(basename "$CHART")"
		echo ".. image:: ../${CHART}"
		echo "   :target: ../${CHART}"
		echo "   :width: 100%"
		echo ""
	done
}

while getopts "d:hi:t:" opt; do
	case $opt in
	d)
		DBNAME=$OPTARG
		;;
	i)
		INDIR=$OPTARG
		;;
	h)
		usage
		exit 0
		;;
	t)
		TITLE=$OPTARG
		;;
	\?)
		usage
		exit 1
		;;
	esac
done

if [ "$INDIR" = "" ]; then
	error "input path was not specified with -i"
fi

if [ "$DBNAME" = "" ]; then
	error "dbname was not specified with -d"
fi

OUTDIR="${INDIR}/db/${DBNAME}"
mkdir -p "$OUTDIR"
if [ ! -d "$OUTDIR" ]; then
	error "could not create directory $OUTDIR"
fi

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

$(image_links)
__EOF__
