#!/bin/sh
#
# Shell script to start the XL Satellite
#

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
SATELLITE_OPTS="-Xmx1024m $SATELLITE_OPTS"

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

cd "$SATELLITE_HOME"

SATELLITE_SERVER_CLASSPATH='conf'

wrapper_conf_file=$SATELLITE_HOME/conf/xl-satellite-wrapper-linux.conf

# Get JVM options
if [ -z "$SATELLITE_OPTS" ] ; then
  SATELLITE_OPTS=`sed -n 's/^wrapper.java.additional.\([0-9]*\) *= *\(.*\)/\2/p' "$wrapper_conf_file" | tr '\n' ' '`
fi

# Build XL Satellite server classpath
classpath_dirs=`sed -n 's/^wrapper.java.classpath.\([0-9]*\)=\(.*[^*]\)$/\2/p' "$wrapper_conf_file" | tr '\n' ':'`
classpath_dirs=`echo $classpath_dirs | sed 's/.$//'`

SATELLITE_SERVER_CLASSPATH="${classpath_dirs}"

all_files_to_list=`sed -n 's/^wrapper.java.classpath.\([0-9]*\)=\(.*\)\/\*$/\2 /p' "$wrapper_conf_file" | tr '\n' ' '`
all_files_to_list="$all_files_to_list -name '*.jar'"
all_files=`echo $all_files_to_list | xargs find`

#`ls hotfix/lib/*.jar 2>/dev/null`
for each in $all_files
do
  if [ -f $each ]; then
    SATELLITE_SERVER_CLASSPATH=${SATELLITE_SERVER_CLASSPATH}:${each}
  fi
done

for each in `ls hotfix/satellite-lib/*.jar 2>/dev/null`
do
  if [ -f $each ]; then
    SATELLITE_SERVER_CLASSPATH=${SATELLITE_SERVER_CLASSPATH}:${each}
  fi
done

RESTART_EXIT_CODE=242

start_xl_satellite ()
{
 $JAVACMD $SATELLITE_OPTS $SATELLITE_LOG_OPTS -classpath "${SATELLITE_SERVER_CLASSPATH}" com.xebialabs.satellite.SatelliteBootstrapper "$@"
 rc=$?
}

# Run XL Satellite server
start_xl_satellite

while [ $rc = $RESTART_EXIT_CODE ]
do
    echo "Restarting XL-Satellite";

    start_xl_satellite

done
