#!/usr/bin/env bash

set -e

CURRENT_DIR=$PWD

# Magic sauce
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$SCRIPT_DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null && pwd )"

if [[ ! -d ${SCRIPT_DIR}/../logs ]]; then
  mkdir ${SCRIPT_DIR}/../logs
fi

FUSIONAUTH_JAVA_DIR=${SCRIPT_DIR}/../java

# Download Java if we are not yet setup, or the version is not the target version.
if [ "$(uname -s)" = "Darwin" ]; then
  JAVA_PATH=${FUSIONAUTH_JAVA_DIR}/jre1.8.0_171.jre
elif [ "$(uname -s)" = "Linux" ]; then
  JAVA_PATH=${FUSIONAUTH_JAVA_DIR}/jre1.8.0_171
fi

if [ ! -e ${FUSIONAUTH_JAVA_DIR}/current ] || [ ! -d ${JAVA_PATH} ]; then
  if ! hash curl; then
    echo "curl is not installed. Please install curl and try again."
    exit 1
  fi
  mkdir -p ${FUSIONAUTH_JAVA_DIR}
  cd ${FUSIONAUTH_JAVA_DIR}
  echo "Downloading Java"
  if [ "$(uname -s)" = "Darwin" ]; then
    curl -O --progress-bar https://storage.googleapis.com/inversoft_products_j098230498/java/jre/jre-macos-1.8.0+u171.tar.gz
    tar xfz jre-macos-1.8.0+u171.tar.gz
    rm -f current
    ln -s jre1.8.0_171.jre current
    rm jre-macos-1.8.0+u171.tar.gz
  elif [ "$(uname -s)" = "Linux" ]; then
    curl -O --progress-bar https://storage.googleapis.com/inversoft_products_j098230498/java/jre/jre-linux-1.8.0+u171.tar.gz
    tar xfz jre-linux-1.8.0+u171.tar.gz
    rm -f ./current
    ln -s ./jre1.8.0_171 current
    rm jre-linux-1.8.0+u171.tar.gz
  fi
fi

# Search
echo -e "Starting fusionauth-search ... \c"
if [[ -f ${SCRIPT_DIR}/../fusionauth-search/elasticsearch/bin/elasticsearch ]]; then
  if pgrep -f fusionAuthSearchEngine87AFBG16 > /dev/null; then
    echo "skipped, already running."
  else
    cd ${SCRIPT_DIR}/../fusionauth-search/elasticsearch/bin
    nohup ./elasticsearch < /dev/null >> ${SCRIPT_DIR}/../logs/fusionauth-search.log 2>&1 &
    disown
    echo "done."
    echo "  --> Logging to ${SCRIPT_DIR}/../logs/fusionauth-search.log"
  fi
else
  echo " skipped, not installed"
fi

# App
echo -e "Starting fusionauth-app ... \c"
if [[ -f ${SCRIPT_DIR}/../fusionauth-app/apache-tomcat/bin/catalina.sh ]]; then
  cd ${SCRIPT_DIR}/../fusionauth-app/apache-tomcat/bin
  nohup ./catalina.sh start < /dev/null >> ${SCRIPT_DIR}/../logs/fusionauth-app.log 2>&1 &
  disown
  echo "done."
  echo "  --> Logging to ${SCRIPT_DIR}/../logs/fusionauth-app.log"
else
  echo " skipped, not installed"
fi

cd ${CURRENT_DIR}
