#!/bin/bash
#
#  Copyright 2005-2014 Red Hat, Inc.
#
#  Red Hat 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.

### Helper functions

jvmArgs() {
  if [ -z "$FABRIC8_JVM_ARGS" ]; then
    cat ${APP_BASE}/etc/jvm.config
  else
    echo "$FABRIC8_JVM_ARGS"
  fi
}

### Helper functions ends

APP_USER=""
SERVICE="process"

SERVICE_NAME="$FABRIC8_RUNTIME_ID"
if [ -f "${SERVICE_NAME}" ] ; then
  SERVICE_NAME="$SERVICE"
fi

#
# Discover the APP_BASE from the location of this script.
#
if [ -z "$APP_BASE" ] ; then
  ## resolve links - $0 may be a link to apollo's home
  PRG="$0"
  saveddir=`pwd`

  # need this for relative symlinks
  dirname_prg=`dirname "$PRG"`
  cd "$dirname_prg"

  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

  APP_BASE=`dirname "$PRG"`
  cd "$saveddir"

  # make it fully qualified
  APP_BASE=`cd "$APP_BASE/.." && pwd`
  export APP_BASE
fi
PID_FILE="${APP_BASE}/var/${SERVICE}.pid"

# Redirect process output to log files
APP_CONSOLE_CMD="${APP_BASE}/logs/cmd.log"
APP_CONSOLE_OUT="${APP_BASE}/logs/out.log"
APP_CONSOLE_ERR="${APP_BASE}/logs/err.log"

# Add the jars in the lib dir
CLASSPATH=""
for file in "$APP_BASE"/lib/*.jar
do
    if [ -z "$CLASSPATH" ]; then
        CLASSPATH="$file"
    else
        CLASSPATH="$CLASSPATH:$file"
    fi
done
for file in "$APP_BASE"/lib/*.war
do
    if [ -z "$CLASSPATH" ]; then
        CLASSPATH="$file"
    else
        CLASSPATH="$CLASSPATH:$file"
    fi
done
CLASSPATH="$CLASSPATH:$APP_BASE/classes"

JVM_DEBUG_ARGS="$FABRIC8_JVM_DEBUG_ARGS"
if [ -z "$JVM_DEBUG_ARGS" ]; then
  if [ ! -z "$FABRIC8_JVM_DEBUG" ] && [ "$FABRIC8_JVM_DEBUG" == 'TRUE' ]; then
    JVM_DEBUG_ARGS='-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005'
  fi
fi

JVM_EXEC="java"
JAVA_AGENT="$FABRIC8_JAVA_AGENT"
JVM_ARGS=`jvmArgs`
APP_ARGS="$FABRIC8_MAIN_ARGS"
MAIN_JAR="$APP_BASE/lib/main.jar"
MAIN_CLASS="$FABRIC8_JAVA_MAIN"
JAVA_AGENT="$FABRIC8_JAVA_AGENT"
SYSTEM_PROPERTIES="$FABRIC8_SYSTEM_PROPERTIES"
if [ -f "${STOP_TIMEOUT}" ] ; then
  STOP_TIMEOUT="30"
fi

# Source the /etc/defaults script if it exists so it can modify the 
# env vars setup so far..
if [ -f "${APP_BASE}/etc/defaults" ] ; then
  . "${APP_BASE}/etc/defaults"
fi

if [ ! -z "$APP_USER" -a ! `id -un` = "$APP_USER" ] ; then
  # re-run the launch under the right user id...
  exec sudo -n -u ${APP_USER} $0 $@
fi

status() {
  if [ -f "${PID_FILE}" ] ; then
    pid=`cat "${PID_FILE}"`
    # check to see if it's gone...
    ps -p ${pid} > /dev/null
    if [ $? -eq 0 ] ; then
      return 1
    else
      rm "${PID_FILE}"
    fi
  fi
  return 0
}

stop() {
  echo "Gracefully Stopping ${SERVICE_NAME} within ${STOP_TIMEOUT} second(s)"

  if [ -f "${PID_FILE}" ] ; then
    pid=`cat "${PID_FILE}"`
    kill $@ ${pid} > /dev/null
  fi
  
  for num in $(seq 1 $STOP_TIMEOUT); do
    status
    if [ $? -eq 0 ] ; then
      return 0
    fi
    sleep 1
  done
  echo "Could not gracefully stop ${SERVICE_NAME} with pid: ${pid} within $STOP_TIMEOUT second(s)"
  return 1
}

start() {

  echo "Starting ${SERVICE_NAME}"
  status
  if [ $? -eq 1 ] ; then
    echo "Already running."
    return 1
  fi

  if [ -z "$MAIN_CLASS" ]; then
    RUN_COMMAND="${JVM_EXEC} ${JVM_DEBUG_ARGS} ${JAVA_AGENT} ${JVM_ARGS} ${SYSTEM_PROPERTIES} -classpath ${CLASSPATH} -jar ${MAIN_JAR} ${APP_ARGS}"
  else
    RUN_COMMAND="${JVM_EXEC} ${JVM_DEBUG_ARGS} ${JAVA_AGENT} ${JVM_ARGS} ${SYSTEM_PROPERTIES} -classpath ${CLASSPATH} ${MAIN_CLASS} ${APP_ARGS}"
  fi

  echo "Running:" > ${APP_CONSOLE_CMD}
  echo "$RUN_COMMAND" >> ${APP_CONSOLE_CMD}
  echo >> ${APP_CONSOLE_CMD}
  echo "Environment variables:" >> ${APP_CONSOLE_CMD}
  env | sort | grep FABRIC >> ${APP_CONSOLE_CMD}

  echo "Running $RUN_COMMAND"

  # If you have bash, then you can use the 'exec -a newname' syntax to rename the java process.
  if [ -x "/bin/bash" ] ; then
    echo exec -a ${SERVICE} $RUN_COMMAND | nohup /bin/bash -s > ${APP_CONSOLE_OUT} 2> ${APP_CONSOLE_ERR} &
  elif [ -x "/usr/bin/bash" ] ; then
    echo exec -a ${SERVICE} $RUN_COMMAND | nohup /usr/bin/bash -s > ${APP_CONSOLE_OUT} 2> ${APP_CONSOLE_ERR} &
  else 
    nohup $RUN_COMMAND > ${APP_CONSOLE_OUT} 2> ${APP_CONSOLE_ERR} &
  fi

  pid="$!"
  mkdir -p `dirname ${PID_FILE}` > /dev/null 2> /dev/null
  echo $pid > "${PID_FILE}"

  # check to see if stays up...
  sleep 1
  status
  if [ $? -eq 0 ] ; then
    echo "Could not start ${SERVICE_NAME}"
    return 1
  fi
  echo "${SERVICE_NAME} is now running (${pid})"
  return 0
}

case $1 in
  start)
    start
    exit $?
  ;;

  force-stop)
    echo "Forcibly Stopping ${SERVICE_NAME}"
    stop -9
    exit $?
  ;;

  stop)
    stop
    exit $?
  ;;

  restart)
    echo "Restarting ${SERVICE_NAME}"
    stop
    status
    if [ $? -eq 1 ] ; then
      echo "${SERVICE_NAME} did not stop cleanly within the time so killing it..."
      force-stop
    fi
    start
    exit $?
  ;;

  status)
    status
    if [ $? -eq 0 ] ; then
      echo "${SERVICE_NAME} is stopped"
    else
      echo "${SERVICE_NAME} is running (${pid})"
    fi
    exit 0
  ;;

  *)
    echo "Usage: $0 {start|stop|restart|force-stop|status}" >&2
    exit 2
  ;;
esac
