#!/bin/sh
#
# Shell script to start the XL Deploy CLI
#

absdirname ()
{
  _dir="`dirname \"$1\"`"
  cd "$_dir"
  echo "`pwd`"
}

resolvelink() {
  _dir=`dirname "$1"`
  _dest=`readlink "$1"`
  case "$_dest" in
  /* ) echo "$_dest" ;;
  *  ) echo "$_dir/$_dest" ;;
  esac
}

# Get Java executable
if [ -z "$JAVA_HOME" ] ; then
  JAVACMD=java
else
  JAVACMD="${JAVA_HOME}/bin/java"
fi

# Get JVM options
if [ -z "$DEPLOYIT_CLI_OPTS" ] ; then
  DEPLOYIT_CLI_OPTS="-Xmx512m "
fi

# Get XL Deploy cli home dir
if [ -z "$DEPLOYIT_CLI_HOME" ] ; then
  self="$0"
  if [ -h "$self" ]; then
    self=`resolvelink "$self"`
  fi
  BIN_DIR=`absdirname "$self"`
  DEPLOYIT_CLI_HOME=`dirname "$BIN_DIR"`
elif [ ! -d "$DEPLOYIT_CLI_HOME" ] ; then
  echo "Directory $DEPLOYIT_CLI_HOME does not exist"
  exit 1
fi

# Switch for unsupported terminans (to run it from installer)
if [ "$UNSUPORTED_TERMINAL" ] ; then
  TERMINAL_OPTS="-Djline.terminal=jline.UnsupportedTerminal"
fi

cd "$DEPLOYIT_CLI_HOME"

# Build XL Deploy cli classpath
DEPLOYIT_CLI_CLASSPATH='conf'
for each in `ls hotfix/*.jar lib/*.jar plugins/*.jar 2>/dev/null`
do
  if [ -f $each ]; then
    DEPLOYIT_CLI_CLASSPATH=${DEPLOYIT_CLI_CLASSPATH}:${each}
  fi
done

if [ ! -z "$EXTRA_DEPLOYIT_CLI_CLASSPATH" ] ; then
  DEPLOYIT_CLI_CLASSPATH=${DEPLOYIT_CLI_CLASSPATH}:${EXTRA_DEPLOYIT_CLI_CLASSPATH}
fi

# Run XL Deploy cli
$JAVACMD $DEPLOYIT_CLI_OPTS -classpath "${DEPLOYIT_CLI_CLASSPATH}" $TERMINAL_OPTS com.xebialabs.deployit.cli.Cli "$@"
res=$?
if [ $res != 0 ] ; then
  exit $res
fi
