# Pre installation script

# Ensure that the proper version of Java exists on the system

java_version() {
# The one argument is the location of java (either $JAVA_HOME or a potential
# candidate for JAVA_HOME.
  JAVA="$1"/bin/java
  "$JAVA" -version 2>&1 | grep "\(java\|openjdk\) version" | awk '{ print substr($3, 2, length($3)-2); }'
}

check_if_correct_java_version() {

# If the string is empty return non-zero code.  We don't want false positives if /bin/java is
# a valid java version because that will leave java8_home unset and the init.d scripts will
# use the default java version, which may not be java 8.
  if [ -z $1 ] ; then
    return 1
  fi

# The one argument is the location of java (either $JAVA_HOME or a potential
# candidate for JAVA_HOME).
  JAVA_VERSION=$(java_version "$1")
  JAVA_UPDATE=$(echo $JAVA_VERSION | cut -d'_' -f2)
  JAVA_MAJOR=$(echo $JAVA_VERSION | cut -d'.' -f1)
  if [[ ("$JAVA_MAJOR" -ge "11") ]]; then
    echo "JAVA_HOME=$1" > /tmp/presto_env.sh
    return 0
  elif [[ ("$JAVA_VERSION" > "1.8") && ($JAVA_UPDATE -ge 161) ]]; then
    echo "JAVA_HOME=$1" > /tmp/presto_env.sh
    return 0
  else
    return 1
  fi
}

# if Java version of $JAVA_HOME is not 1.8 update 161 (8u161) and is not Oracle Java, then try to find it again below
if ! check_if_correct_java_version "$JAVA_HOME"; then
  java_found=false
  for candidate in \
      /usr/lib/jvm/java-11-* \
      /usr/lib/jvm/jdk1.8* \
      /usr/lib/jvm/jre1.8* \
      /usr/lib/jvm/java-8-oracle* \
      /usr/java/jdk1.8* \
      /usr/java/jre1.8* \
      /usr/jdk64/jdk1.8* \
      /usr/lib/jvm/default-java \
      /usr/java/default \
      / \
      /usr ; do
      if [ -e "$candidate"/bin/java ]; then
        if check_if_correct_java_version "$candidate" ; then
          java_found=true
          break
        fi
      fi
  done
fi

# if no appropriate java found
if [ "$java_found" = false ]; then
  cat 1>&2 <<EOF
+======================================================================+
|      Error: Required Java version could not be found                 |
+----------------------------------------------------------------------+
| Please download the latest Oracle JDK/JRE from the Java web site     |
|       > http://www.oracle.com/technetwork/java/javase/downloads <    |
|                                                                      |
| Presto requires Java 1.8 update 161 (8u161)                          |
| NOTE: This script will attempt to find Java whether you install      |
|       using the binary or the RPM based installer.                   |
+======================================================================+
EOF
  exit 1
fi

getent group presto >/dev/null || /usr/sbin/groupadd -r presto
getent passwd presto >/dev/null || /usr/sbin/useradd --comment "Presto" -s /sbin/nologin -g presto -r -d /var/lib/presto presto
