#!/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
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------
# WINDUP Startup script
#
# Required Environment vars:
# ------------------
#   JAVA_HOME - location of a JRE home directory
#
# Optional Environment Variables
# ------------------
#   WINDUP_HOME - location of WINDUP's installed home dir
#   WINDUP_OPTS - parameters passed to the Java VM when running WINDUP
#   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=()
WINDUP_DEBUG_ARGS=()
QUOTED_ARGS=()
RUN_OPENREWRITE=()
TRANSFORM_PROJECT_PATH=()
OPENREWRITE_QUOTED_ARGS=()
OPENREWRITE_GOAL=( "dryRun" )

## 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.
## Value set to 10000 to be aligned with windup-web-distribution
WE_NEED=10000
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
  if [ $MAX_HARD -lt $WE_NEED ] ; then 
    echo ""
    echo "[WARNING] The limit ($MAX_HARD) for open files is too low and could make WINDUP 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
  MIN_WE_NEED_OR_CAN_HAVE=$(( $MAX_HARD > $WE_NEED ? $WE_NEED : $MAX_HARD ))
  echo "Increasing the maximum of open files to $MIN_WE_NEED_OR_CAN_HAVE."
  ulimit -S -n $MIN_WE_NEED_OR_CAN_HAVE
fi


## resolve links - $0 may be a link to WINDUP'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

saveddir=`pwd`

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

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

cd "$saveddir"

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

  if [ "$1" = "--debug" ] ; then
    WINDUP_DEBUG_ARGS=( "-Xdebug" "-Xnoagent" "-Djava.compiler=NONE" "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" )
  fi
  
  if [ "$1" = "--openrewrite" ] ; then
    RUN_OPENREWRITE=( "yes" ) 
  elif [ "$1" = "--input" ] ; then
    TRANSFORM_PROJECT_PATH=("$2")
  elif [ "$1" = "$TRANSFORM_PROJECT_PATH" ] ; then
  	pathfound=true
  elif [ "$1" = "--goal" ] ; then
    OPENREWRITE_GOAL=("$2")
  elif [ "$1" = "$OPENREWRITE_GOAL" ] ; then
  	goalfound=true
  else
  	OPENREWRITE_QUOTED_ARGS+=("$1")
  fi 
  
  QUOTED_ARGS+=("$1")
  
  shift
done

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

if [ -f "$HOME/.winduprc" ] ; then
  . "$HOME/.winduprc"
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 "$WINDUP_HOME" ] ; then
    # Detect if this script is in a WINDUP directory
    if [ ! -f "$SCRIPT_HOME/cli-version.txt" ] ; then
        # If it is, then use it as WINDUP_HOME
        echo "Resetting WINDUP_HOME to $SCRIPT_HOME (from: $WINDUP_HOME)"

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

if [ -z "$WINDUP_HOME" ] ; then
  ## resolve links - $0 may be a link to WINDUP'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

  saveddir=`pwd`

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

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

  cd "$saveddir"
fi

echo Using the CLI at $WINDUP_HOME

# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
  [ -n "$WINDUP_HOME" ] &&
    WINDUP_HOME=`cygpath --unix "$WINDUP_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 "$WINDUP_HOME" ] &&
    WINDUP_HOME="`(cd "$WINDUP_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

MODULES=""
JAVAVER=`"$JAVACMD" -version 2>&1 | head -n 1 | cut -d '"' -f2`
case $JAVAVER in
"11"*)
  MODULES="--add-modules=java.se"
 ;;
"17"*)
  MODULES="--add-modules=java.se --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.stream=ALL-UNNAMED"
 ;;
*)
	echo " Error: a Java 11 or 17 JRE is required to run WINDUP; found [$JAVACMD -version == $JAVAVER]."
	exit 1
 ;;
esac


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

WINDUP_MAIN_CLASS=org.jboss.windup.bootstrap.Bootstrap

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

#
if [ -r "$WINDUP_HOME/addons/" ] ; then
  ADDONS_DIR=("--immutableAddonDir" "$WINDUP_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 "$WINDUP_OPTS" ] ; then
  if [ -n "$MAX_MEMORY" ] ; then
    WINDUP_OPTS="-Xmx$MAX_MEMORY -XX:MaxMetaspaceSize=$MAX_METASPACE_SIZE -XX:ReservedCodeCacheSize=$RESERVED_CODE_CACHE_SIZE"
  else
    WINDUP_OPTS="-XX:MaxMetaspaceSize=$MAX_METASPACE_SIZE -XX:ReservedCodeCacheSize=$RESERVED_CODE_CACHE_SIZE"
  fi
fi

WINDUP_OPTS="$WINDUP_OPTS $FILE_DESCRIPTOR_OPTS";

if [ "$RUN_OPENREWRITE" != "" ] ; then
	( cd "$TRANSFORM_PROJECT_PATH"; exec mvn org.openrewrite.maven:rewrite-maven-plugin:4.44.0:"${OPENREWRITE_GOAL}" "${OPENREWRITE_QUOTED_ARGS[@]}" )
	exit 0;

fi

exec "$JAVACMD" $MODULES "${WINDUP_DEBUG_ARGS[@]}" $WINDUP_OPTS -Dforge.standalone=true -Dforge.home="${WINDUP_HOME}" -Dwindup.home="${WINDUP_HOME}" \
   -cp "${WINDUP_HOME}"/lib/'*' $WINDUP_MAIN_CLASS "${QUOTED_ARGS[@]}" "${ADDONS_DIR[@]}"
