# Load properties that become environment variables
# NOTE: it would be possible to specify a normal java properties file after the 'start.jar'

JETTY_BIN_DIR=`dirname "$0"`
if [ ${JETTY_BIN_DIR#/} == ${JETTY_BIN_DIR} ]; then
    JETTY_BIN_DIR="`pwd`/${JETTY_BIN_DIR}"
fi

JETTY_PID_FILE="$JETTY_BIN_DIR/../openbis.pid"

source "$JETTY_BIN_DIR/../etc/jetty.properties"
source "$JETTY_BIN_DIR/../etc/openbis.conf"
cd "$JETTY_BIN_DIR"/..

if [ -n "$JAVA_HOME" ]; then
    JVM="$JAVA_HOME"/bin/java
else
    JVM="`which java`"
fi 

JETTY_LIB_PATH="$JETTY_BIN_DIR"/../webapps/openbis/WEB-INF/jython-lib

awkBin()
{
  # We need a awk that accepts variable assignments with '-v'
  case `uname -s` in
    "SunOS")
      echo "nawk"
      return
      ;;
  esac
  # default
  echo "awk"
}

isPIDRunning()
{
  if [ "$1" = "" ]; then
    return 1
  fi
  if [ "$1" = "fake" ]; then # for unit tests
    return 0
  fi
  # This will have a return value of 0 on BSDish systems
  isBSD="`ps aux > /dev/null 2>&1; echo $?`"
  AWK=`awkBin`
  if [ "$isBSD" = "0" ]; then
    if [ "`ps aux | $AWK -v PID=$1 '{if ($2==PID) {print "FOUND"}}'`" = "FOUND" ]; then
      return 0
    else
      return 1
    fi
  else
    if [ "`ps -ef | $AWK -v PID=$1 '{if ($2==PID) {print "FOUND"}}'`" = "FOUND" ]; then
      return 0
    else
      return 1
    fi
  fi
}

checkNotRoot()
{
  if [ $UID -eq 0 ]; then
    echo "openBIS Data Store Server cannot run as user 'root'." > /dev/stderr
    exit 1
  fi
}

printStatus()
{
  if [ "$1" == "-q" ]; then
    QUIET=1
  fi
  if [ -f $JETTY_PID_FILE ]; then
    PID=`cat $JETTY_PID_FILE`
    isPIDRunning $PID
    if [ $? -eq 0 ]; then
      test -z "$QUIET" && echo "openBIS Application Server is running (pid $PID)"
      return 0
    else
      test -z "$QUIET" && echo "openBIS Application is dead (stale pid $PID)"
      return 1
    fi
  else
    test -z "$QUIET" && echo "openBIS Application is not running."
    return 2
  fi
}
