#!/bin/sh

# 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.

# -----------------------------------------------------------------------------
# Apache Maven Startup Script
#
# Environment Variable Prerequisites
#
#   JAVA_HOME           (Optional) Points to a Java installation.
#   MAVEN_ARGS          (Optional) Arguments passed to Maven before CLI arguments, separated by white space.
#                       Single or double quotes group a value containing white space.
#   MAVEN_OPTS          (Optional) Java runtime options used when Maven is executed.
#   MAVEN_SKIP_RC       (Optional) Flag to disable loading of mavenrc files.
#   MAVEN_DEBUG_OPTS    (Optional) Specify the debug options to use. Default value is "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${MAVEN_DEBUG_ADDRESS}" when --debug is used
#   MAVEN_DEBUG_ADDRESS (Optional) Set the debug address. Default value is "localhost:8000"
# -----------------------------------------------------------------------------

if [ -z "$MAVEN_SKIP_RC" ] ; then

  if [ -f /usr/local/etc/mavenrc ] ; then
    . /usr/local/etc/mavenrc
  fi

  if [ -f /etc/mavenrc ] ; then
    . /etc/mavenrc
  fi

  if [ -f "$HOME/.mavenrc" ] ; then
    . "$HOME/.mavenrc"
  fi

fi

# Note on echo vs printf: several POSIX shells (dash and the other Almquist
# derivatives commonly installed as /bin/sh) expand backslash escapes in echo.
# Windows paths are full of backslashes, so C:\tmp\build would be printed with a
# tab in place of \t. Every value that may hold a path is therefore emitted with
# printf '%s' rather than echo; plain literals may still use echo.

# OS specific support. $var _must_ be set to either true or false.
# MINGW* matches the MinGW32/MinGW64 shells (e.g. Git Bash, the shell used by
# "shell: bash" steps of GitHub Actions Windows runners), MSYS* the MSYS2 shell.
# All of them run on top of a POSIX emulation layer that mangles POSIX paths
# passed to native (Windows) processes such as the JVM, so paths have to be
# converted to their native Windows form explicitly.
cygwin=false;
mingw=false;
case "`uname`" in
  CYGWIN*) cygwin=true;;
  MINGW*|MSYS*) mingw=true;;
esac

# Cygwin and MSYS2 both ship cygpath(1), but bail out of the path conversion if
# it is unexpectedly missing: substituting empty paths would break the launch in
# a way that is much harder to diagnose than keeping the POSIX paths.
if $cygwin || $mingw ; then
  if ! ( \unset -f command; \command -v cygpath ) > /dev/null 2>&1 ; then
    echo "Warning: cygpath was not found on the PATH, Apache Maven cannot convert paths to the Windows format." >&2
    echo "Some plugins may misbehave when they receive POSIX paths." >&2
    cygwin=false
    mingw=false
  fi
fi

# A cygpath(1) from an unrelated POSIX emulation layer (e.g. the one shipped in
# an Anaconda installation) can be found on the PATH first. It re-roots every
# POSIX path under its own installation prefix, so all converted values point to
# non-existing directories and the JVM dies with a bare ClassNotFoundException.
# cygpath can convert relative paths too, but the current directory is the only
# path that is known to exist at this point: verify that its Windows form can be
# found on disk before trusting any of the later conversions.
if $cygwin || $mingw ; then
  _cygpath_bin=`( \unset -f command; \command -v cygpath )` || _cygpath_bin=
  _probe_win=`cygpath --windows "$PWD"` || _probe_win=
  if [ -z "$_probe_win" ] || [ ! -d "$_probe_win" ] ; then
    printf '%s\n' "Warning: the cygpath found on the PATH (\"$_cygpath_bin\") does not convert paths to" >&2
    printf '%s\n' "usable Windows paths (\"$PWD\" converts to \"$_probe_win\", which does not exist)," >&2
    printf '%s\n' "so Apache Maven cannot convert paths to the Windows format." >&2
    printf '%s\n' "Some plugins may misbehave when they receive POSIX paths." >&2
    cygwin=false
    mingw=false
  fi
fi

## resolve links - $0 may be a link to Maven's home
PRG="$0"

# need this for relative symlinks
while [ -h "$PRG" ] ; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG="`dirname "$PRG"`/$link"
  fi
done

saveddir=`pwd`

MAVEN_HOME=`dirname "$PRG"`/..

# make it fully qualified
MAVEN_HOME=`cd "$MAVEN_HOME" && pwd`

cd "$saveddir"

CLASSWORLDS_CONF="$MAVEN_HOME/bin/m2.conf"

# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if $cygwin || $mingw ; then
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi

if [ -n "$JAVA_HOME" ] ; then
  if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
    # IBM's JDK on AIX uses strange locations for the executables
    JAVACMD="$JAVA_HOME/jre/sh/java"
  else
    JAVACMD="$JAVA_HOME/bin/java"

    if [ ! -x "$JAVACMD" ] ; then
      echo "The JAVA_HOME environment variable is not defined correctly, so Apache Maven cannot be started." >&2
      printf 'JAVA_HOME is set to "%s", but "$JAVA_HOME/bin/java" does not exist.\n' "$JAVA_HOME" >&2
      exit 1
    fi
  fi
else
  JAVACMD="`\\unset -f command; \\command -v java`"

  if [ ! -x "$JAVACMD" ] ; then
    echo "The java(1) command does not exist in PATH nor is JAVA_HOME set, so Apache Maven cannot be started." >&2
    exit 1
  fi
fi

# Early scan of the CLI arguments so that version-only invocations can be
# answered straight from this script, without booting the full Maven JVM. The
# banner is assembled to match org.apache.maven.cling.utils.CLIReportingUtils
# #showVersion (see print_fast_version below). Compact single-dash tokens
# (e.g. -qv, -qV) are honoured, but only when composed exclusively of the safe
# chars q/v/V/X/e, mirroring the relevant Commons CLI short options.
VERSION_AND_EXIT=false
SHOW_VERSION=false
QUIET=false
VERBOSE=false
MAIN_CLASS_OVERRIDE=false
FAST_VERSION_PRINTED=false
for arg in "$@"; do
  if [ "$arg" = "--" ] ; then
    break
  fi
  case $arg in
    -v|--version) VERSION_AND_EXIT=true ;;
    -V|--show-version) SHOW_VERSION=true ;;
    -q|--quiet) QUIET=true ;;
    -X|--debug) VERBOSE=true ;;
    --enc|--shell|--up|--val) MAIN_CLASS_OVERRIDE=true ;;
    -[qvVXe]*)
      case $arg in
        *v*) VERSION_AND_EXIT=true ;;
        *V*) SHOW_VERSION=true ;;
      esac
      case $arg in
        *q*) QUIET=true ;;
        *X*) VERBOSE=true ;;
      esac
      ;;
    *) ;;
  esac
done

# Read a single `key=value` from a properties file. Unresolved `${...}`
# placeholders are treated as absent, mirroring the reduce() logic used by the
# JVM version reporting.
read_property() {
  _file=$1
  _key=$2
  if [ -f "$_file" ] ; then
    _value=`sed -n "s/^$_key=//p" "$_file"`
    case $_value in
      \$\{*|"") ;;
      *) printf '%s\n' "$_value" ;;
    esac
  fi
}

# Extract a JVM system property value from a `java -XshowSettings:properties`
# dump (the properties are emitted on stderr as `    java.version = 17.0.10`).
show_settings_property() {
  _settings=$1
  _key=$2
  if [ -n "$_settings" ] ; then
    printf '%s\n' "$_settings" | sed -n "s/^ *$_key *= *//p" | head -n 1
  fi
}

# Render the version banner. When quiet, only the bare version is printed,
# matching CLIReportingUtils#showVersionMinimal.
print_fast_version() {
  _settings=$1
  _quiet=$2

  _version_file="$MAVEN_HOME/bin/maven.version.properties"

  _mvn_name=`read_property "$_version_file" distributionName`
  _mvn_short=`read_property "$_version_file" distributionShortName`
  _mvn_version=`read_property "$_version_file" version`
  _mvn_build=`read_property "$_version_file" buildNumber`

  if [ -z "$_mvn_version" ] ; then
    # Fallback to the (versioned) core jar filename when the version file is
    # not present, e.g. when running straight from a source checkout.
    for _jar in "$MAVEN_HOME"/lib/maven-core-*.jar ; do
      if [ -f "$_jar" ] ; then
        _mvn_version=`printf '%s' "$_jar" | sed -e 's#.*maven-core-##' -e 's#\.jar$##'`
        break
      fi
    done
  fi

  if [ -z "$_mvn_name" ] ; then
    _mvn_name="Apache Maven"
  fi
  if [ -z "$_mvn_short" ] ; then
    _mvn_short="Maven"
  fi
  if [ -z "$_mvn_version" ] ; then
    _mvn_version="<version unknown>"
  fi

  if $_quiet ; then
    printf '%s\n' "$_mvn_version"
    return 0
  fi

  printf '%s %s' "$_mvn_name" "$_mvn_version"
  if [ -n "$_mvn_build" ] ; then
    printf ' (%s)' "$_mvn_build"
  fi
  printf '\n'

  printf '%s home: %s\n' "$_mvn_short" "$MAVEN_HOME"

  _java_version=`show_settings_property "$_settings" java.version`
  _java_vendor=`show_settings_property "$_settings" java.vendor`
  _java_home=`show_settings_property "$_settings" java.home`
  printf 'Java version: %s, vendor: %s, runtime: %s\n' \
    "${_java_version:-<unknown Java version>}" "${_java_vendor:-<unknown vendor>}" "${_java_home:-<unknown runtime>}"

  _lang=`show_settings_property "$_settings" user.language`
  _country=`show_settings_property "$_settings" user.country`
  _encoding=`show_settings_property "$_settings" file.encoding`
  _timezone=`show_settings_property "$_settings" user.timezone`
  if [ -z "$_timezone" ] ; then
    # The settings dump does not carry the time zone; derive it the same way
    # the JVM does (TZ wins, then /etc/localtime) when possible.
    if [ -n "$TZ" ] && [ -r "/usr/share/zoneinfo/$TZ" ] ; then
      _timezone="$TZ"
    elif [ -h /etc/localtime ] ; then
      _timezone=`readlink /etc/localtime`
      _timezone=`printf '%s' "$_timezone" | sed 's#^.*zoneinfo/##'`
    elif [ -r /etc/timezone ] ; then
      _timezone=`cat /etc/timezone`
    fi
  fi
  _locale="$_lang"
  if [ -n "$_country" ] ; then
    _locale="$_lang"_"$_country"
  fi
  printf 'Default locale: %s, platform encoding: %s, time zone: %s\n' \
    "$_locale" "${_encoding:-<unknown encoding>}" "${_timezone:-<unknown>}"

  _os_name=`show_settings_property "$_settings" os.name`
  _os_version=`show_settings_property "$_settings" os.version`
  _os_arch=`show_settings_property "$_settings" os.arch`
  _os_name=`printf '%s' "$_os_name" | tr '[:upper:]' '[:lower:]'`
  _os_version=`printf '%s' "$_os_version" | tr '[:upper:]' '[:lower:]'`
  _os_arch=`printf '%s' "$_os_arch" | tr '[:upper:]' '[:lower:]'`

  _os_family="unknown"
  case "$_os_name" in
    *windows*) _os_family="windows" ;;
    *mac*|darwin) _os_family="mac" ;;
    *os/2*) _os_family="os/2" ;;
    *dos*) _os_family="dos" ;;
    *)
      if [ -n "$_os_name" ] ; then
        _os_family="unix"
      fi
      ;;
  esac
  printf 'OS name: "%s", version: "%s", arch: "%s", family: "%s"\n' \
    "$_os_name" "$_os_version" "$_os_arch" "$_os_family"
}

# Combined Java 17 gate and JVM settings probe. Version invocations reuse the
# settings dump to render the banner without starting Maven itself; every other
# invocation only relies on the exit status, exactly like the former probe.
HAS_SETTINGS=false
VERSION_SETTINGS=
if $VERSION_AND_EXIT || $SHOW_VERSION ; then
  if ! $VERBOSE && ! $MAIN_CLASS_OVERRIDE ; then
    if VERSION_SETTINGS=`"$JAVACMD" --enable-native-access=ALL-UNNAMED -XshowSettings:properties -version 2>&1` ; then
      HAS_SETTINGS=true
    fi
  fi
fi
if ! $HAS_SETTINGS ; then
  if ! "$JAVACMD" --enable-native-access=ALL-UNNAMED -version >/dev/null 2>&1; then
    echo "Error: Apache Maven 4.x requires Java 17 or newer to run." >&2
    "$JAVACMD" -version >&2
    echo "Please upgrade your Java installation or set JAVA_HOME to point to a compatible JDK." >&2
    exit 1
  fi
fi

if $HAS_SETTINGS ; then
  if $VERSION_AND_EXIT ; then
    print_fast_version "$VERSION_SETTINGS" $QUIET
    exit 0
  fi
  # -V/--show-version: print the banner now and let the JVM run the build
  # without printing it a second time.
  print_fast_version "$VERSION_SETTINGS" $QUIET
  FAST_VERSION_PRINTED=true
fi

# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
(
  basedir=`find_file_argument_basedir "$@"`
  wdir="$basedir"
  while :
  do
    if [ -d "$wdir"/.mvn ] ; then
      basedir=$wdir
      break
    fi
    if [ "$wdir" = '/' ] ; then
      break
    fi
    wdir=`cd "$wdir/.."; pwd`
  done
  printf '%s\n' "$basedir"
)
}

find_file_argument_basedir() {
(
  basedir=`pwd`

  found_file_switch=0
  for arg in "$@"; do
    if [ ${found_file_switch} -eq 1 ]; then
      if [ -d "${arg}" ]; then
        basedir=`cd "${arg}" && pwd -P`
      elif [ -f "${arg}" ]; then
        basedir=`dirname "${arg}"`
        basedir=`cd "$basedir" && pwd -P`
      fi
      # If the argument does not exist (e.g. a Cygwin/MSYS path that will be
      # converted later, or a genuinely missing file), fall back to the current
      # directory.  The Java layer validates the path and produces the proper
      # error message when the file is truly absent.
      break
    fi
    if [ "$arg" = "-f" -o "$arg" = "--file" ]; then
      found_file_switch=1
    fi
  done
  printf '%s\n' "$basedir"
)
}

# concatenates all lines of a file and replaces variables
# Uses Java-based parser to handle all special characters correctly
# This avoids shell parsing issues with pipes, quotes, @, and other special characters
# and ensures POSIX compliance (no xargs -0, awk, or complex sed needed)
# Set MAVEN_DEBUG_SCRIPT=1 to enable debug logging
concat_lines() {
  if [ -f "$1" ]; then
    # JvmConfigParser is shipped precompiled: source-launch mode would compile it
    # on every invocation, which costs several times the actual parsing

    # Debug logging
    if [ -n "$MAVEN_DEBUG_SCRIPT" ]; then
      printf '[DEBUG] Found jvm.config file at: %s\n' "$1" >&2
      printf '[DEBUG] Running JvmConfigParser with Java: %s\n' "$JAVACMD" >&2
      printf '[DEBUG] Parser arguments: %s %s %s\n' \
        "-cp $MAVEN_HOME/bin JvmConfigParser" "$1" "$MAVEN_PROJECTBASEDIR_NATIVE" >&2
    fi

    # Verify Java is available
    "$JAVACMD" -version >/dev/null 2>&1 || {
      echo "Error: Java not found. Please set JAVA_HOME." >&2
      return 1
    }

    # Run the parser
    # Capture stdout for JVM options; capture stderr separately so JVM notices
    # (e.g. JAVA_TOOL_OPTIONS) do not pollute MAVEN_OPTS.
    parser_stderr_file=$(mktemp "${TMPDIR:-/tmp}/mvn-jvm-config-stderr.XXXXXX" 2>/dev/null || echo "${TMPDIR:-/tmp}/mvn-jvm-config-stderr.$$")
    trap 'rm -f "$parser_stderr_file"' EXIT INT TERM
    parser_output=$("$JAVACMD" -cp "$MAVEN_HOME/bin" JvmConfigParser "$1" "$MAVEN_PROJECTBASEDIR_NATIVE" 2>"$parser_stderr_file")
    parser_exit=$?

    if [ -n "$MAVEN_DEBUG_SCRIPT" ]; then
      echo "[DEBUG] JvmConfigParser exit code: $parser_exit" >&2
      printf '[DEBUG] JvmConfigParser output: %s\n' "$parser_output" >&2
      if [ -s "$parser_stderr_file" ]; then
        while IFS= read -r parser_err_line || [ -n "$parser_err_line" ]; do
          printf '[DEBUG] JvmConfigParser stderr: %s\n' "$parser_err_line" >&2
        done < "$parser_stderr_file"
      fi
    fi

    if [ $parser_exit -ne 0 ]; then
      # Parser failed - print comprehensive error information
      echo "ERROR: JvmConfigParser failed with exit code $parser_exit" >&2
      printf '  jvm.config path: %s\n' "$1" >&2
      printf '  Maven basedir: %s\n' "$MAVEN_PROJECTBASEDIR" >&2
      printf '  Java command: %s\n' "$JAVACMD" >&2
      echo "  Parser output:" >&2
      # Print captured stderr (parser exceptions/diagnostics) and stdout so no diagnostic info is dropped
      if [ -s "$parser_stderr_file" ]; then
        while IFS= read -r parser_err_line || [ -n "$parser_err_line" ]; do
          printf '    %s\n' "$parser_err_line" >&2
        done < "$parser_stderr_file"
      fi
      if [ -n "$parser_output" ]; then
        printf '%s\n' "$parser_output" | while IFS= read -r parser_out_line || [ -n "$parser_out_line" ]; do
          printf '    %s\n' "$parser_out_line" >&2
        done
      fi
      rm -f "$parser_stderr_file" 2>/dev/null || :
      trap - EXIT INT TERM
      exit 1
    fi

    rm -f "$parser_stderr_file" 2>/dev/null || :
    trap - EXIT INT TERM
    printf '%s\n' "$parser_output"
  fi
}

MAVEN_PROJECTBASEDIR="`find_maven_basedir "$@"`"

# Under Cygwin/MinGW the POSIX form of the project base directory is required by
# the shell (to locate .mvn/jvm.config), while the JVM and everything it hands
# the value over to (plugins, jvm.config placeholders) expects the native
# Windows form. Compute the latter upfront and keep both around.
MAVEN_PROJECTBASEDIR_NATIVE="$MAVEN_PROJECTBASEDIR"
if $cygwin || $mingw ; then
  MAVEN_PROJECTBASEDIR_NATIVE=`cygpath --windows "$MAVEN_PROJECTBASEDIR"`
fi

# Read JVM config and append to MAVEN_OPTS, preserving special characters
_jvm_config="`concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config"`"
if [ -n "$_jvm_config" ]; then
  if [ -n "$MAVEN_OPTS" ]; then
    MAVEN_OPTS="$MAVEN_OPTS $_jvm_config"
  else
    MAVEN_OPTS="$_jvm_config"
  fi
fi
if [ -n "$MAVEN_DEBUG_SCRIPT" ]; then
  printf '[DEBUG] Final MAVEN_OPTS: %s\n' "$MAVEN_OPTS" >&2
fi
LAUNCHER_JAR=""
for _jar in "$MAVEN_HOME"/boot/*.jar; do
  [ -f "$_jar" ] && LAUNCHER_JAR="${LAUNCHER_JAR:+$LAUNCHER_JAR:}$_jar"
done
LAUNCHER_CLASS=org.codehaus.plexus.classworlds.launcher.Launcher
JLINE_NATIVE_PATH="$MAVEN_HOME/lib/jline-native"
MODULES_DIR="$MAVEN_HOME/lib/modules"

# For Cygwin and MinGW, switch paths to Windows format before running java(1) command
if $cygwin || $mingw ; then
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --windows "$JAVA_HOME"`
  LAUNCHER_JAR=`cygpath --windows --path "$LAUNCHER_JAR"`
  CLASSWORLDS_CONF=`cygpath --windows "$CLASSWORLDS_CONF"`
  MAVEN_HOME=`cygpath --windows "$MAVEN_HOME"`
  # converted separately, appending to the already converted MAVEN_HOME would
  # produce a path mixing both separators, e.g. C:\maven/lib/jline-native
  JLINE_NATIVE_PATH=`cygpath --windows "$JLINE_NATIVE_PATH"`
  MODULES_DIR=`cygpath --windows "$MODULES_DIR"`
fi

# Module-path and native access flags require a JDK that can read the module jars.
# The probe includes --module-path so it fails on JDKs that cannot read the module descriptors.
# Fall back to ALL-UNNAMED so that --enable-native-access is always granted on JDK 22+,
# even when the module-path probe fails (older JDK, missing lib/modules/, locked-down env).
MAVEN_MODULE_OPTS="--enable-native-access=ALL-UNNAMED"
if "$JAVACMD" --module-path "$MODULES_DIR" --add-modules ALL-MODULE-PATH --enable-native-access=org.jline.terminal.ffm -version >/dev/null 2>&1; then
  MAVEN_MODULE_OPTS="--module-path \"$MODULES_DIR\" --add-modules ALL-MODULE-PATH --enable-native-access=org.jline.terminal.ffm,org.jline.nativ"
fi
MAVEN_PROJECTBASEDIR="$MAVEN_PROJECTBASEDIR_NATIVE"

# MNG-8056: Under Cygwin, the JVM is a native Windows process and cannot resolve
# Cygwin-style POSIX paths (e.g. /cygdrive/c/...) directly.  The internal paths
# (MAVEN_HOME, CLASSWORLDS_CONF, JAVA_HOME, …) are already converted above, but
# user-supplied paths passed via -f/--file, -s/--settings, -gs/--global-settings, -t/--toolchains, -gt/--global-toolchains,
# -ps/--project-settings, -is/--install-settings, -it/--install-toolchains,
# -l/--log-file, and -af/--at-file reach the JVM unconverted.
# The loop below rewrites only those argument values that begin with '/' (absolute
# POSIX paths); relative paths and already-Windows paths are left unchanged.
# MinGW/MSYS2 perform automatic path mangling, so the fix is Cygwin-only.
if $cygwin ; then
  _np=false
  _count=$#
  while [ $_count -gt 0 ]; do
    _a="$1"
    shift
    if $_np; then
      case "$_a" in
        /*) _a=$(cygpath --windows "$_a") ;;
      esac
      _np=false
    else
      case "$_a" in
        -f|--file|-s|--settings|-gs|--global-settings|-t|--toolchains|-gt|--global-toolchains|-ps|--project-settings|-is|--install-settings|-it|--install-toolchains|-l|--log-file|-af|--at-file)
          _np=true ;;
        --file=/*|--settings=/*|--global-settings=/*|--toolchains=/*|--global-toolchains=/*|--project-settings=/*|--install-settings=/*|--install-toolchains=/*|--log-file=/*|--at-file=/*)
          _flag="${_a%%=*}"
          _path="${_a#*=}"
          _a="${_flag}=$(cygpath --windows "${_path}")"
          ;;
      esac
    fi
    set -- "$@" "$_a"
    _count=$(( _count - 1 ))
  done
fi

handle_args() {
  while [ $# -gt 0 ]; do
    case $1 in
      --debug)
        if [ -z "$MAVEN_DEBUG_OPTS" ] ; then
          MAVEN_DEBUG_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${MAVEN_DEBUG_ADDRESS:-localhost:8000}"
        else
          echo "Ignoring --debug option as MAVEN_DEBUG_OPTS is already set"
        fi
        ;;
      --yjp)
        if [ ! -f "$YJPLIB" ]; then
          echo "Error: Unable to autodetect the YJP library location. Please set YJPLIB variable" >&2
          exit 1
        fi
        MAVEN_OPTS="-agentpath:$YJPLIB=onexit=snapshot,onexit=memory,tracing,onlylocal $MAVEN_OPTS"
        ;;
      --enc)
        MAVEN_MAIN_CLASS="org.apache.maven.cling.MavenEncCling"
        ;;
      --shell)
        MAVEN_MAIN_CLASS="org.apache.maven.cling.MavenShellCling"
        ;;
      --up)
        MAVEN_MAIN_CLASS="org.apache.maven.cling.MavenUpCling"
        ;;
      --val)
        MAVEN_MAIN_CLASS="org.apache.maven.cling.MavenValCling"
        ;;
      *)
        ;;
    esac
    shift
  done
}

handle_args "$@"
MAVEN_MAIN_CLASS=${MAVEN_MAIN_CLASS:=org.apache.maven.cling.MavenCling}

# Build base command string for eval (only contains Maven-controlled values)
cmd="\"$JAVACMD\" \
  $MAVEN_OPTS \
  $MAVEN_DEBUG_OPTS \
  $MAVEN_MODULE_OPTS \
  -classpath \"$LAUNCHER_JAR\" \
  \"-Dclassworlds.conf=$CLASSWORLDS_CONF\" \
  \"-Dmaven.home=$MAVEN_HOME\" \
  \"-Dmaven.mainClass=$MAVEN_MAIN_CLASS\" \
  \"-Dlibrary.jline.path=$JLINE_NATIVE_PATH\" \
  \"-Dmaven.multiModuleProjectDirectory=$MAVEN_PROJECTBASEDIR\""

# The JVM option must precede the main class on the command line, otherwise it
# would be treated as a plain Maven argument rather than a system property.
if [ "$FAST_VERSION_PRINTED" = "true" ] ; then
  cmd="$cmd \"-Dmaven.version.printed=true\""
fi

cmd="$cmd $LAUNCHER_CLASS"

# MAVEN_ARGS is only passed for the default Maven build command (MavenCling),
# not for sub-commands like --up, --enc, --shell or --val which have their own options.
#
# Its words are separated by white space, and single or double quotes group a word
# containing white space, so that a path with a space can be passed.
# Nothing else is interpreted: no backslash escape, no ${...} placeholder, no globbing
# and no command substitution, so the values reach Maven as they were written.
# A word is made of adjacent quoted and unquoted parts, and "" is an empty word.
# The words go in front of the user arguments, "$@" is rotated to get them in order.
if [ "$MAVEN_MAIN_CLASS" = "org.apache.maven.cling.MavenCling" ] && [ -n "$MAVEN_ARGS" ]; then
  maven_args_user_count=$#
  maven_args_rest=$MAVEN_ARGS
  maven_args_word=
  maven_args_in_word=false
  maven_args_quote=
  maven_args_tab=`printf '\t'`
  maven_args_nl='
'
  while [ -n "$maven_args_rest" ]; do
    maven_args_tail=${maven_args_rest#?}
    maven_args_char=${maven_args_rest%"$maven_args_tail"}
    maven_args_rest=$maven_args_tail
    if [ -n "$maven_args_quote" ]; then
      if [ "$maven_args_char" = "$maven_args_quote" ]; then
        maven_args_quote=
      else
        maven_args_word=$maven_args_word$maven_args_char
      fi
    else
      case $maven_args_char in
        '"' | "'")
          maven_args_quote=$maven_args_char
          maven_args_in_word=true
          ;;
        ' ' | "$maven_args_tab" | "$maven_args_nl")
          if [ "$maven_args_in_word" = true ]; then
            set -- "$@" "$maven_args_word"
            maven_args_word=
            maven_args_in_word=false
          fi
          ;;
        *)
          maven_args_word=$maven_args_word$maven_args_char
          maven_args_in_word=true
          ;;
      esac
    fi
  done
  if [ -n "$maven_args_quote" ]; then
    echo "Warning: MAVEN_ARGS has an unterminated $maven_args_quote quote, the rest of the value is treated as part of the last word" >&2
  fi
  if [ "$maven_args_in_word" = true ]; then
    set -- "$@" "$maven_args_word"
  fi
  while [ "$maven_args_user_count" -gt 0 ]; do
    set -- "$@" "$1"
    shift
    maven_args_user_count=$((maven_args_user_count - 1))
  done
fi

if [ -n "$MAVEN_DEBUG_SCRIPT" ]; then
  echo "[DEBUG] Launching JVM with command:" >&2
  printf '[DEBUG]   %s' "$cmd" >&2
  printf ' "%s"' "$@" >&2; echo >&2
fi

# The arguments ("$@") are passed outside the eval'd string to preserve literal
# values (backslashes, ${...} placeholders) without shell re-parsing.
# Only the base command uses eval for MAVEN_OPTS word splitting.
eval exec "$cmd" '"$@"'
