#!/bin/bash

# ----------------------------------------------------------------------------
# Copyright 2012 Red Hat, Inc. and/or its affiliates.
#
# Licensed under the Eclipse Public License version 1.0, available at
# http://www.eclipse.org/legal/epl-v10.html
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------
# MTA Startup script
#
# Required Environment vars:
# ------------------
#   JAVA_HOME - location of a JRE home directory
#
# Optional Environment Variables
# ------------------
#   MTA_HOME - location of MTA's installed home dir
#   MTA_OPTS - parameters passed to the Java VM when running MTA
#   MAX_MEMORY - Maximum Java Heap (example: 2048m)
#   MAX_METASPACE_SIZE - Maximum Metaspace size (example: 256m)
#   RESERVED_CODE_CACHE_SIZE - Hotspot code cache size (example: 128m)
# -----------------------------------------------------------------------
ADDONS_DIR=()
MTA_DEBUG_ARGS=()
QUOTED_ARGS=()

## Increase the open file limit if low, to what we need or at least to the hard limit.
## Complain if the hard limit is lower than what we need.
WE_NEED=1024
MAX_HARD=$(ulimit -H -n);
MAX_SOFT=$(ulimit -S -n);

if [ $MAX_SOFT == 'unlimited' ] ; then MAX_SOFT=$WE_NEED; fi;
if [ $MAX_HARD == 'unlimited' ] ; then MAX_HARD=$WE_NEED; fi;

if [ $MAX_SOFT -lt $WE_NEED ] || [ $MAX_HARD -lt $WE_NEED ]  ; then

  echo ""
  echo "[WARNING] The limits ($MAX_SOFT/$MAX_HARD) for open files is too low and could make MTA unstable. Please increase them to at least $WE_NEED."
  echo ""
  echo "    {RHEL & Fedora} Limits are typically configured in /etc/security/limits.conf"
  echo "     -> Follow instructions of https://access.redhat.com/solutions/60746"
  echo ""
  echo "    {MacOS} Limits are typically configured in /etc/launchd.conf or /etc/sysctl.conf."
  echo "     -> Execute this script: https://gist.github.com/Maarc/d13b1e70f191d5b527a24d39dd3e2569 and restart your operating system."
  echo ""

fi


## resolve links - $0 may be a link to MTA's home
SCRIPT_HOME="$0"

# need this for relative symlinks
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

SCRIPT_HOME=`dirname "$SCRIPT_HOME"`/..

# make it fully qualified
SCRIPT_HOME=`cd "$SCRIPT_HOME" && pwd`

echo "Changing to script home: $SCRIPT_HOME"
cd $SCRIPT_HOME

while [ "$1" != "" ] ; do

  if [ "$1" = "--debug" ] ; then
    MTA_DEBUG_ARGS=( "-Xdebug" "-Xnoagent" "-Djava.compiler=NONE" "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" )
  fi

  QUOTED_ARGS+=("$1")
  shift
done

if [ -f /etc/mtarc ] ; then
  . /etc/mtarc
fi

if [ -f "$HOME/.mtarc" ] ; then
  . "$HOME/.mtarc"
fi

# OS specific support.  $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
  CYGWIN*) cygwin=true ;;
  MINGW*) mingw=true;;
  Darwin*) darwin=true
           ## Prevent "Too many open files" on Mac.
           FILE_DESCRIPTOR_OPTS="-XX:-MaxFDLimit";
           if [ -z "$JAVA_VERSION" ] ; then
             JAVA_VERSION="1.7+"
           fi
           if [ -z "$JAVA_HOME" ] ; then
             JAVA_HOME="`/usr/libexec/java_home --version $JAVA_VERSION`"
           fi
           ;;
esac

if [ -z "$JAVA_HOME" ] ; then
  if [ -r /etc/gentoo-release ] ; then
    JAVA_HOME=`java-config --jre-home`
  fi
fi

if [ -n "$MTA_HOME" ] ; then
    # Detect if this script is in a MTA directory
    if [ ! -f "$SCRIPT_HOME/mta-cli-version.txt" ] ; then
        # If it is, then use it as MTA_HOME
        echo "Resetting MTA_HOME to $SCRIPT_HOME (from: $MTA_HOME)"

        # Set it to blank and we will recalculate it later on
        MTA_HOME="$SCRIPT_HOME"
    fi
fi

if [ -z "$MTA_HOME" ] ; then
  ## resolve links - $0 may be a link to MTA's home
  PRG="$0"

  # need this for relative symlinks
  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

  MTA_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  MTA_HOME=`cd "$MTA_HOME" && pwd`
fi

echo Using MTA at $MTA_HOME

# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
  [ -n "$MTA_HOME" ] &&
    MTA_HOME=`cygpath --unix "$MTA_HOME"`
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
  [ -n "$CLASSPATH" ] &&
    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi

# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
  [ -n "$MTA_HOME" ] &&
    MTA_HOME="`(cd "$MTA_HOME"; pwd)`"
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
  # TODO classpath?
fi

if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD="`which java`"
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  We cannot execute $JAVACMD"
  exit 1
fi

JAVAVER=`"$JAVACMD" -version 2>&1`
case $JAVAVER in
*1.[8-9]*) ;;
*1.[1-7]*)
	echo " Error: a Java 1.8 or higher JRE is required to run MTA; found [$JAVACMD -version == $JAVAVER]."
	exit 1
 ;;
esac


if [ -z "$JAVA_HOME" ] ; then
  echo "Warning: JAVA_HOME environment variable is not set."
fi

MTA_MAIN_CLASS=org.jboss.windup.bootstrap.Bootstrap

# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
  [ -n "$MTA_HOME" ] &&
    MTA_HOME=`cygpath --path --windows "$MTA_HOME"`
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
  [ -n "$HOME" ] &&
    HOME=`cygpath --path --windows "$HOME"`
fi

#
if [ -r "$MTA_HOME/addons/" ] ; then
  ADDONS_DIR=("--immutableAddonDir" "$MTA_HOME/addons/")
fi

if [ -z "$MAX_METASPACE_SIZE" ] ; then
  MAX_METASPACE_SIZE="256m"
fi

if [ -z "$RESERVED_CODE_CACHE_SIZE" ] ; then
  RESERVED_CODE_CACHE_SIZE="128m"
fi

if [ -z "$MTA_OPTS" ] ; then
  if [ -n "$MAX_MEMORY" ] ; then
    MTA_OPTS="-Xmx$MAX_MEMORY -XX:MaxMetaspaceSize=$MAX_METASPACE_SIZE -XX:ReservedCodeCacheSize=$RESERVED_CODE_CACHE_SIZE"
  else
    MTA_OPTS="-XX:MaxMetaspaceSize=$MAX_METASPACE_SIZE -XX:ReservedCodeCacheSize=$RESERVED_CODE_CACHE_SIZE"
  fi
fi

MTA_OPTS="$MTA_OPTS $FILE_DESCRIPTOR_OPTS";

JAVA_TOOL_OPTIONS=""

$JAVACMD "${MTA_DEBUG_ARGS[@]}" $MTA_OPTS -Dforge.standalone=true -Dforge.home=${MTA_HOME} -Dwindup.home=${MTA_HOME} \
   -cp ${MTA_HOME}/lib/'*' $MTA_MAIN_CLASS "${QUOTED_ARGS[@]}" "${ADDONS_DIR[@]}"
