#!/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-2 Authors
#

if [ "x${DBT2DBNAME}" = "x" ]; then
	echo "DBT2DBNAME not defined."
	exit 1
fi

usage()
{
	echo "Usage: dbt2-pgsql-load-stored-procs -t <c|plpgsql> [-i <SHAREDIR>] [-l <PORT>]"
	echo "    c       - C stored functions"
	echo "    plpgsql - pl/pgsql stored functions"
}

# Check if we are in an AppImage environment and set SHAREDIR appropriately,
# otherwise expect the stored functions to be install into the default location
# as specified by pg_config.
if [ ! "${APPDIR}" = "" ]; then
	SHAREDIR="${APPDIR}/usr/share/postgresql"
elif ! command -v pg_config > /dev/null; then
	SHAREDIR=$(pg_config --sharedir)
fi

TYPE="plpgsql"
while getopts "i:l:t:" OPT; do
	case ${OPT} in
	i)
		SHAREDIR=${OPTARG}
		if [ ! -d "${SHAREDIR}" ]; then
			echo "ERROR: directory does not exist: ${SHAREDIR}"
			exit 1
		fi
		;;
	l)
		PORT=${OPTARG}
		;;
	t)
		TYPE=${OPTARG}
		;;
	esac
done

if [ -z "${TYPE}" ]; then
	usage
	exit 1
fi

if [ ! "x${PORT}" = "x" ]; then
	PORTARG="-p ${PORT}"
fi

PSQL="psql -v ON_ERROR_STOP=1 -X ${PORTARG} -e -d ${DBT2DBNAME}"

if [ "${TYPE}" = "plpgsql" ]; then
	if [ "${SHAREDIR}" = "" ]; then
		echo "ERROR: postgresql share directory not detected or not specified"
		exit 1
	fi

	echo "loading pl/pgsql stored functions..."
	${PSQL} -f ${SHAREDIR}/delivery.sql || exit 1
	${PSQL} -f ${SHAREDIR}/new_order.sql || exit 1
	${PSQL} -f ${SHAREDIR}/order_status.sql || exit 1
	${PSQL} -f ${SHAREDIR}/payment.sql || exit 1
	${PSQL} -f ${SHAREDIR}/stock_level.sql || exit 1
elif [ "${TYPE}" = "c" ]; then
	echo "loading C stored functions..."
	$PSQL -c "CREATE EXTENSION dbt2;" || exit 1
else
	echo "unknown stored function type: ${TYPE}"
	exit 2
fi
