#!/bin/sh

# Determine LD_HOME
if [ -z "$LD_HOME" ] ; then
  ## resolve links
  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`

  LD_HOME=`dirname "$PRG"`

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

  cd "$saveddir"
fi

# Setup log directory
LD_LOGS=$LD_HOME/logs

[ ! -d "$LD_LOGS" ] && mkdir $LD_LOGS

LD_TEMP=$LD_HOME/temp
LD_MAVEN_LOCAL_REPOSITORY=$LD_TEMP/maven
export LD_MAVEN_LOCAL_REPOSITORY

MAVEN_HOME=$LD_HOME/maven
export MAVEN_HOME

LD_PREFIX=`grep 'prefix=' $LD_HOME/livedata.properties | sed -e "s/prefix=//g" -e "s/#.*//"`
LD_USER=`grep 'user=' $LD_HOME/livedata.properties | sed -n '/^user=/p' | sed -e 's/user=//' -e "s/#.*//"`
LD_PASSWORD=`grep 'password=' $LD_HOME/livedata.properties | sed -n '/^password=/p' | sed -e 's/password=//' -e "s/#.*//"`
LD_VERSION=`grep 'version=' $LD_HOME/livedata.properties | sed -n '/^version=/p' | sed -e 's/version=//' -e "s/#.*//"`

export LD_PREFIX
export LD_USER
export LD_PASSWORD

if [ -z "$LD_VERSION" ] ; then
  LD_VERSION="RELEASE"
fi
export LD_VERSION

# Check maven profile
if [ -n "$LD_PREFIX" ] ; then
  LD_MAVEN_LOCAL_REPOSITORY=$LD_TEMP/"$LD_PREFIX"maven
  export LD_MAVEN_LOCAL_REPOSITORY
fi

MAVEN_OPTS="$MAVEN_OPTS \
  -Dmaven.repo.local="$LD_MAVEN_LOCAL_REPOSITORY" \
  -Doracle.jdbc.Trace=true \
  -XX:+HeapDumpOnOutOfMemoryError \
  -Xmx1024m \
  -Dlogback.configurationFile="$LD_HOME/conf/logback.xml" \
  -Djdk.http.auth.tunneling.disabledSchemes="" \
  -Dcom.revere.logs.dir="$LD_HOME/logs" \
  -Dcom.revere.admcfg.dir="$LD_HOME" \
  -Dld.dist.version="3.25.5" \
  -Dcom.revere.ld.tempDirectory="$LD_TEMP" \
  -Dcom.revere.ld.client.home="$LD_HOME" \
  -Dld.prefix="$LD_PREFIX" \
     "
export MAVEN_OPTS

chmod u+x "$MAVEN_HOME/bin/mvn"

# Execute maven
"$MAVEN_HOME/bin/mvn" \
  -U -s "$LD_HOME/conf/settings.xml" \
  -Dartifact="com.revere.ld:ld-client2:$LD_VERSION" \
  -DmainClass="com.revere.ld.client.LdClient" \
  com.revere.jshell:jshell-maven-plugin:exec-main $@

exit $?
