#!/bin/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
#
#     https://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.

#   Edited for Gentoo Linux

EPREFIX=""

# Extract launch and ant arguments, (see details below).
ant_exec_args=
no_config=false
use_jikes_default=false
ant_exec_debug=false
show_help=false

if [ -z "$PROTECT_NL" ]; then
  PROTECT_NL=true
  os=`uname -s`
  rel=`uname -r`
  # heirloom bourne-shell used by Solaris 10 is not POSIX
  # it lacks features necessary to protect trailing NL from subshell trimming
  if [ "$os" = SunOS -a "$rel" = "5.10" ]; then
    PROTECT_NL=false
  fi
fi

for arg in "$@"; do
  if [ "$arg" = "--noconfig" ]; then
    no_config=true
  elif [ "$arg" = "--usejikes" ]; then
    use_jikes_default=true
  elif [ "$arg" = "--execdebug" ]; then
    ant_exec_debug=true
  elif [ my"$arg" = my"--h" -o my"$arg" = my"--help"  ]; then
    show_help=true
    ant_exec_args="$ant_exec_args -h"
  else
    if [  my"$arg" = my"-h" -o  my"$arg" = my"-help" ]; then
      show_help=true
    fi

    if [ "$PROTECT_NL" = "true" ]; then
      # pad the value with X to protect trailing NLs from subshell output trimming
      esc_arg="${arg}X"
    else
      esc_arg="${arg}"
    fi

    # wrap all arguments as "" strings, escape any internal back-slash, double-quote, $, or back-tick characters
    #  use printf to avoid echo interpretation behaviors such as escapes and line continuation
    # Mac bsd_sed does not support group-0, so pattern uses group-1
    # Solaris sed only processes lines with trailing newline, passing in an extra newline
    # subshell (heirloom and posix) will trim the added trailing newline
    esc_arg="`printf '%s\n' "$esc_arg" | sed -e 's@\([$\"\`\\]\)@\\\\\\1@g' `"

    if [ "$PROTECT_NL" = "true" ]; then
      # remove the padding X added above, this syntax is POSIX compatible but not heirloom-sh
      esc_arg="${esc_arg%X}"
    fi
    quoted_arg="\"$esc_arg\""

    if $ant_exec_debug; then
      # using printf to avoid echo line continuation and escape interpretation
      printf "arg       : %s\n" "$arg"
      printf "quoted_arg: %s\n" "$quoted_arg"
    fi
    ant_exec_args="$ant_exec_args $quoted_arg"
  fi
done

# Source/default ant configuration
if $no_config; then
  rpm_mode=false
  usejikes=$use_jikes_default
else
  # load system-wide ant configuration (ONLY if ANT_HOME has NOT been set)
  if [ -z "$ANT_HOME" -o "$ANT_HOME" = "${EPREFIX}/usr/share/ant" ]; then
    if [ -f "${EPREFIX}/etc/ant.conf" ]; then
      . "${EPREFIX}"/etc/ant.conf
    fi
  fi

  # load user ant configuration
  if [ -f "$HOME/.ant/ant.conf" ]; then
    . $HOME/.ant/ant.conf
  fi
  if [ -f "$HOME/.antrc" ]; then
    . "$HOME/.antrc"
  fi

  # provide default configuration values
  if [ -z "$rpm_mode" ]; then
    rpm_mode=false
  fi
  if [ -z "$usejikes" ]; then
    usejikes=$use_jikes_default
  fi
fi

export WANT_JAVA_CONFIG=2

# Always get JAVA_HOME from java-config, unless ANT_RESPECT_JAVA_HOME is set
# Use GENTOO_VM to change which VM is used instead.
if [[ -z "${ANT_RESPECT_JAVA_HOME}" || -z "${JAVA_HOME}" ]]; then
	export JAVA_HOME="$(java-config -g JAVA_HOME)"
fi

if [ -z $JAVA_HOME ] ; then
  echo 'Error: No JDK found!'
  echo "Try using java-config script to set your JDK"
  echo "Remember that you need a JDK not a JRE"
  exit 1
fi

if [[ -z "${ANT_HOME}" ]] ; then
	ANT_HOME="${EPREFIX}"/usr/share/ant
fi

# set ANT_LIB location
ANT_LIB="${ANT_HOME}/lib"

if [ -z "$JAVACMD" ]; then
  if [ -n "$JAVA_HOME" ]; then
      JAVACMD="$JAVA_HOME/bin/java"
  else
    JAVACMD=`which java 2> /dev/null `
    if [ -z "$JAVACMD" ]; then
      JAVACMD=java
    fi
  fi
fi

if [ ! -x "$JAVACMD" ]; then
  echo "We cannot run Java, please ensure you have Java installed."
  echo "  We have tried to execute $JAVACMD but failed."
  echo "If you have installed Java in a unusual place you can set JAVA_HOME"
  echo "to the directory containing the Java installation."
  exit 1
fi

if [ -z "$LOCALCLASSPATH" ] ; then
  LOCALCLASSPATH=$ANT_LIB/ant-launcher.jar
else
  LOCALCLASSPATH=$ANT_LIB/ant-launcher.jar:$LOCALCLASSPATH
fi

# if ANT_TASKS is not set, default to "all"
ANT_TASKS="${ANT_TASKS:-all}"

# if ANT_TASKS is set to "all", get the tasks list from /usr/share/ant/tasks/
if [[ "${ANT_TASKS}" == "all" ]]; then
	ANT_TASKS=""
	# but only if it exists
	if [[ -d "${EPREFIX}"/usr/share/ant/tasks ]]; then
		ANT_TASKS="${ANT_TASKS} ${EPREFIX}"/usr/share/ant/tasks/*
	fi
	if [[ -d "${EPREFIX}"/usr/share/ant/tasks-1.8.2 ]]; then
		ANT_TASKS="${ANT_TASKS} ${EPREFIX}"/usr/share/ant/tasks-1.8.2/*
	fi
# if set to "none", make ANT_TASKS empty list
elif [[ "${ANT_TASKS}" == "none" ]]; then
	ANT_TASKS=""
fi
# otherwise ANT_TASKS defines explicit task list

# construct the tasks list separated with commas to pass to java-config
TASKS_LIST=""
for task in $ANT_TASKS; do
  TASKS_LIST="${TASKS_LIST},$(basename $task)"
done
TASKS_LIST=${TASKS_LIST#,}

# get the classpath for optional tasks and their dependency .jar files
if [[ -n "${TASKS_LIST}" ]] ; then
  ANT_TASKS_CLASSPATH="-lib \"$(java-config -dp ${TASKS_LIST})\""
  ANT_TASKS_LIBPATH="-Djava.library.path=\"$(java-config -di ${TASKS_LIST})\""
else
  ANT_TASKS_CLASSPATH=""
  ANT_TASKS_LIBPATH=""
fi

# determine where to get tools.jar from
if [[ -n "${ANT_RESPECT_JAVA_HOME}" ]]; then
	TOOLS_JAR="${JAVA_HOME}/lib/tools.jar"
else
	TOOLS_JAR="$(java-config --tools)"
fi

if [[ -n "${TOOLS_JAR}" ]] ; then
  LOCALCLASSPATH="$LOCALCLASSPATH:${TOOLS_JAR}"
elif [[ $(java-config -f) != apple-jdk-bin* ]] ; then
  echo "Warning: Unable to determine tools.jar location."
  echo "  If build fails because sun.* classes could not be found,"
  echo "  Make sure you are using a JDK, not JRE as your user/system VM."
  echo "  and that you have java-config version 2.0.30 or above installed."
fi

# Allow Jikes support (off by default)
if $usejikes; then
  ANT_OPTS="$ANT_OPTS -Dbuild.compiler=jikes"
fi

# Show script help if requested
if $show_help; then
  echo $0 '[script options] [options] [target [target2 [target3] ..]]'
  echo 'Script Options:'
  echo '  --help, --h            print this message and ant help'
  echo '  --noconfig             suppress sourcing of /etc/ant.conf,'
  echo '                         $HOME/.ant/ant.conf, and $HOME/.antrc'
  echo '                         configuration files'
  echo '  --usejikes             enable use of jikes by default, unless'
  echo '                         set explicitly in configuration files'
  echo '  --execdebug            print ant exec line generated by this'
  echo '                         launch script'
  echo ''
fi

# Execute ant using eval/exec to preserve spaces in paths,
# java options, and ant args
ant_sys_opts=

if [ -n "$JIKESPATH" ]; then
	ant_sys_opts="-Djikes.class.path=\"$JIKESPATH\""
fi

ant_exec_command="exec \"${JAVACMD}\" ${ANT_OPTS} -classpath \"${LOCALCLASSPATH}\" \
	-Dant.home=\"${ANT_HOME}\" -Dant.library.dir=\"${ANT_LIB}\" ${ant_sys_opts} \
	${ANT_TASKS_LIBPATH} org.apache.tools.ant.launch.Launcher \
	${ANT_TASKS_CLASSPATH} ${ANT_ARGS} -cp \"${CLASSPATH}\""

if $ant_exec_debug; then
  # using printf to avoid echo line continuation and escape interpretation confusion
  printf "%s\n" "$ant_exec_command $ant_exec_args"
fi

eval "$ant_exec_command $ant_exec_args"
