#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# DAFFODIL_CLASSPATH
#
# The Daffodil implementation will look on the classpath for 'includes' and
# 'imports'. To defined additional directories where Daffodil should look for
# files, set the DAFFODIL_CLASSPATH environment variable, for example:
#
#   export DAFFODIL_CLASSPATH="/path/to/imports/:/path/to/includes/"
#
# In addition to defining directories to search for imports and includes, you
# can add a "CatalogManager.properties" file to the DAFFODIL_CLASSPATH to
# direct Daffodil to a relative path location of a user XML Catalog.
#
#
# DAFFODIL_JAVA_OPTS
#
# If you need to specify java options specific to Daffodil, you can set the
# DAFFODIL_JAVA_OPTS environment variable. If not specified, the JAVA_OPTS
# environment variable will be used. If that is not specified, reasonable
# defaults for Daffodil will be defined.

realpath() {
  THISPWD=$PWD
  LNK=$1
  while [ "$LNK" ]; do
    cd "$(dirname "$LNK")" || return
    BN=$(basename "$LNK")
    LNK=$(readlink "$BN")
  done
  REALPATH="$PWD/$BN"
  cd "$THISPWD" || return
  echo "$REALPATH"
}

MAINCLASS=org.apache.daffodil.cli.Main
SCRIPT=$(realpath "$0")			# Full path to script, needed for symlinks
BINDIR=$(dirname "${SCRIPT}")		# Directory script is run in
LIBDIR="$BINDIR/../lib"
CONFDIR="$BINDIR/../conf"
CLASSPATH=$LIBDIR/'*'

if [ -n "$DAFFODIL_JAVA_OPTS" ]; then
	JOPTS="$DAFFODIL_JAVA_OPTS"
elif [ -n "$JAVA_OPTS" ]; then
	JOPTS="$JAVA_OPTS"
fi

if [ -n "$DAFFODIL_CLASSPATH" ]; then
	CLASSPATH="$CLASSPATH:$DAFFODIL_CLASSPATH"
fi

if uname -a | grep -qi cygwin
then
	# if run from cygwin, convert unix paths to windows paths
	CLASSPATH=$(cygpath -apw "$CLASSPATH")
fi

# Prepend additional java options that must be provided. By prepending, a user
# can override options by redefining them in JAVA_OPTS or DAFFODIL_JAVA_OPTS
DEFAULT_JOPTS=(
  "-Xms1024m"
  "-Xmx1024m"
  "-XX:ReservedCodeCacheSize=128m"
)

exec java "${DEFAULT_JOPTS[@]}" $JOPTS -cp "$CLASSPATH" $MAINCLASS "$@"
