#!/bin/sh
#

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

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

M2_HOME=${M2_HOME:-"%%DATADIR%%"}

# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir()
{
  local basedir=$(pwd)
  local wdir=$(pwd)
  while [ "$wdir" != '/' ] ; do
    wdir=$(cd "$wdir/.."; pwd)
    if [ -d "$wdir"/.mvn ] ; then
      basedir=$wdir
      break
    fi
  done
  echo "${basedir}"
}

# concatenates all lines of a file
concat_lines()
{
  if [ -f "$1" ]; then
    echo "$(tr -s '\n' ' ' < "$1")"
  fi
}

MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"

exec "%%LOCALBASE%%/bin/java" $MAVEN_OPTS \
	-classpath "${M2_HOME}/boot/%%CLASSWORLDS_JAR%%" \
	"-Dclassworlds.conf=${M2_HOME}/bin/m2.conf" \
	"-Dmaven.home=${M2_HOME}" \
	"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
	org.codehaus.classworlds.Launcher "$@"
