#!/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 DBT plot runner"
	echo ""
	echo "Usage:"
	echo "  $(basename "$0") TYPE [OPTION]"
	echo
	echo "Set DBTLANG to 'gnuplot', 'R' or 'julia' to select the plotting"
	echo "language, or leave it unset to autodetect in that order."
	echo
}

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

if [ "$1" = "-h" ]; then
	usage
	exit 0
fi

if [ $# -lt 1 ]; then
	usage
	exit 1
fi

if [ "$DBTLANG" = "" ]; then
	# Ordered preference of which language usually runs faster.
	if command -v "gnuplot" > /dev/null 2>&1; then
		DBTLANG="gnuplot"
	elif command -v "R" > /dev/null 2>&1; then
		DBTLANG="R"
	elif command -v "julia" > /dev/null 2>&1; then
		DBTLANG="julia"
	else
		error "'gnuplot', 'julia' nor 'R' detected for post processing"
	fi
fi

case "$DBTLANG" in
gnuplot)
	PPEXT="gnuplot"
	;;
julia)
	PPEXT="jl"
	;;
R)
	PPEXT="r"
	;;
*)
	error "DBTLANG is '${DBTLANG}', set it to 'gnuplot', 'R' or 'julia'," \
			"or unset it to let the script autodetect"
	;;
esac

if ! command -v "$DBTLANG" > /dev/null 2>&1; then
	error "$DBTLANG not detected, install it or set DBTLANG to another" \
			"of 'gnuplot', 'R' or 'julia'"
fi

MODULE="$1"
shift

PSCRIPT="dbt-plot-${MODULE}.${PPEXT}"

if ! command -v "$PSCRIPT" > /dev/null 2>&1; then
	error "$PSCRIPT not found in PATH"
fi

if [ "$DBTLANG" = "julia" ]; then
	# Set up a private, per-user depot so package installation does not
	# interfere with whatever packages already exist.
	DBT_JULIA_DEPOT_PATH="${XDG_CACHE_HOME:-${HOME}/.cache}/dbttools/julia"
	if ! mkdir -p "${DBT_JULIA_DEPOT_PATH}"; then
		error "could not create Julia depot ${DBT_JULIA_DEPOT_PATH}," \
				"set JULIA_DEPOT_PATH to a writable directory"
	fi
	if [ "$JULIA_DEPOT_PATH" = "" ]; then
		export JULIA_DEPOT_PATH="${DBT_JULIA_DEPOT_PATH}"
	else
		export JULIA_DEPOT_PATH="${DBT_JULIA_DEPOT_PATH}:${JULIA_DEPOT_PATH}"
	fi

	# Make sure package dependencies are installed.

	PACKAGES="CSV DataFrames VegaLite"
	for PACKAGE in $PACKAGES; do
		INSTALLED="import Pkg
			exit(haskey(Pkg.project().dependencies, \"${PACKAGE}\") ? 0 : 1)"
		if ! julia -q -e "${INSTALLED}" > /dev/null 2>&1; then
			echo "Installing Julia package ${PACKAGE}..."
			if ! julia -q -e "import Pkg; Pkg.add(\"${PACKAGE}\")"; then
				error "failed to install Julia package ${PACKAGE}"
			fi
		fi
	done
fi

"$PSCRIPT" "$@"
