#!/bin/bash

# include user-defined overrides and customization
if [ -f ~/.sql-dk/environment.sh ]; then # .sql-dk must match with DIR in Constants.java
	. ~/.sql-dk/environment.sh
else
	mkdir -p ~/.sql-dk/
	# link/copy support files for configuration:
	[ -f ~/.sql-dk/environment.sh ] || touch ~/.sql-dk/environment.sh
	[ -f ~/.sql-dk/config.xsd ] || ln -s /usr/share/doc/sql-dk/config.xsd ~/.sql-dk/config.xsd
	[ -f ~/.sql-dk/config.rnc ] || ln -s /usr/share/doc/sql-dk/config.rnc ~/.sql-dk/config.rnc
	[ -f ~/.sql-dk/config.xsl ] || gunzip < /usr/share/doc/sql-dk/config.xsl.gz > ~/.sql-dk/config.xsl # might not work in www browser if just symlinked
fi

# Standard JDBC drivers
[ -n "$STANDARD_JDBC" ] || STANDARD_JDBC=(
	"/usr/share/java/postgresql-jdbc4.jar"
	"/usr/share/java/mysql.jar"
);

# Standard libraries
[ -n "$STANDARD_LIB" ] || STANDARD_LIB=(
	"/usr/share/java/jaxb-api.jar"
	"/usr/share/java/jaxb-runtime.jar"
);
# JAXB library is needed since Java 9 (up to Java 8 it was part of the JRE).
# By default, we use JARs from the distribution.
# Some distributions might contain older versions of the JAXB library (2.3.0)
# that work but generate following waringns:
#   WARNING: An illegal reflective access operation has occurred
#   WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector (file:/usr/share/java/jaxb-runtime.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int)
#   WARNING: Please consider reporting this to the maintainers of com.sun.xml.bind.v2.runtime.reflect.opt.Injector
#   WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
#   WARNING: All illegal access operations will be denied in a future release
# In order to get rid of them, the user can use newer JARs from Maven that are copied into the java/sql-dk/target/lib/ directory during build.
# This is done by adding them in the STANDARD_LIB variable in his environment.sh file.


# Additional JDBC drivers might be specified in CUSTOM_JDBC array
# Plugins (formatters etc.) might be specified in PLUGINS array

# JAR containing SQL-DK application
[ -n "$JAR" ] || JAR="/usr/share/sql-dk/sql-dk.jar";

CLASS_PATH="$JAR";

for e in "${CUSTOM_JDBC[@]}" "${PLUGINS[@]}" "${STANDARD_JDBC[@]}" "${STANDARD_LIB[@]}"; do
	CLASS_PATH="$CLASS_PATH:$e";
done


MAIN_CLASS="info.globalcode.sql.dk.CLIStarter";

LOGGER="-Djava.util.logging.config.class=info.globalcode.sql.dk.logging.LoggerInitializer";
[ -n "$LOG_LEVEL" ] && LOGGER_LEVEL="-Dinfo.globalcode.sql.dk.logging.LoggerInitializer.level=$LOG_LEVEL";

java "${JAVA_OPTIONS[@]}" $LOGGER $LOGGER_LEVEL -cp "$CLASS_PATH" $MAIN_CLASS "$@"
