#!/usr/bin/env bash

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                               #
#       JDK installer script                                                    #
#       Writen by: RBS                                                          #
#       Version: 0.10         Released: 20.01.2023                              #
#                                                                               #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                               #
#     Usage: ./get_jdk_linux_x64.sh version path                                #
#     If version ot path not specified the default values is                    #
#     jdk version 8 and /opt as path                                            #
#     Versions available  8, 11, 17, 19                                         #
#                                                                               #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

__green() {
    printf '\033[1;31;32m'
    printf -- "%b\\n" "$1"
    printf '\033[0m'
}
__red() {
    printf '\033[1;31;40m'
    printf -- "%b\\n" "$1"
    printf '\033[0m'
}
__yellow() {
    printf '\033[1;33;40m'
    printf -- "%b\\n" "$1"
    printf '\033[0m'
}

# Check if the script is running with root permissions
if [ "$(id -u)" -ne 0 ]; then
    __red "The script must be run as root! (you can use sudo)"
    exit 1
fi
# Check if the script is running on 64 bit OS. 
if ! [ "$(getconf LONG_BIT)" = 64 ]
then
    echo
    __red "This is a not an x86_64 OS, make sure to run this script on 64 bit OS ... "
    echo
    exit 1
fi
# Check if the curl installed .
if [ ! -x /usr/bin/curl ] ; then
    command -v curl >/dev/null 2>&1 || { echo >&2 "Please install curl or set it in your path. Aborting."; exit 1; }
fi

jdk_versions=(8 11 17 21)
jdk_def_version=${1:-8}
jdk_install_dir=${2:-/opt}
JDK_LOCATION=$jdk_install_dir/java

declare -A _jdk_urls=(
 ["${jdk_versions[0]}"]="https://cfdownload.adobe.com/pub/adobe/coldfusion/java/java8/java8u401/jdk/jdk-8u401-linux-x64.tar.gz"
 ["${jdk_versions[1]}"]="https://cfdownload.adobe.com/pub/adobe/coldfusion/java/java11/java11022/jdk-11.0.22_linux-x64_bin.tar.gz"
 ["${jdk_versions[2]}"]="https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.tar.gz"
 ["${jdk_versions[3]}"]="https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.tar.gz"
)

if [[ ! "${jdk_versions[*]}" =~ $jdk_def_version ]] ; then
    echo
    __red "   Wrong version number !!!   "
    echo
    __green "   Version can be only ${jdk_versions[*]} "
    echo
  exit 2
fi

if [ ! -d "$jdk_install_dir" ]; then
  if mkdir -p "$jdk_install_dir" > /dev/null 2>&1 ;then
    echo
   __green "OK --- Directory ( ""$jdk_install_dir"" ) created --- "
    echo 
else
    echo
    __red "FAILED"
    echo
    __red "Provided path is not valid directory: $jdk_install_dir"
    echo
    exit 1
 fi
fi

cd "$jdk_install_dir" || exit

if [[ "${jdk_versions[*]}" =~ $jdk_def_version ]] ; then
	_jdk_url="${_jdk_urls[$jdk_def_version]}"
fi

JDK_ARCHIVE=$(awk -F '/' '{print $NF}' <<< "$_jdk_url")

if ! [ -f "$JDK_ARCHIVE" ];
  then
	if curl -sIf "$_jdk_url" |grep -q '200 OK'; then
    __green "Downloading $JDK_ARCHIVE ... "
    echo
    curl -O -j -k -L "$_jdk_url"
	else __yellow  " The URL  ""$_jdk_url""  is unawailable. Please check and update this file."
	exit 2
	fi
 else
    echo 
    __yellow  "Archive file $JDK_ARCHIVE already exist ... installing"
    echo
  fi

JDF=$(tar -tzf "$JDK_ARCHIVE" | head -1  | cut -d "/" -f1)

# Is the file a valid archive?
echo -n "Validating the archive file... "
if gunzip -t "$JDK_ARCHIVE" >/dev/null 2>&1 ; then
    __green "OK"
else
    __red "FAILED"
    echo 
    __yellow "Provided file is not a valid .tar.gz archive: $JDK_ARCHIVE"
    echo 
    exit 1
fi

# Extract the archive
echo -n "Extracting the archive... and creating symlink... "
tar -xf "$JDK_ARCHIVE" -C "$jdk_install_dir"
rm "$JDK_ARCHIVE"

if [ -d "$JDF" ] 
  then 
    chown -R root:root "$JDF"
    ln -nsf "$JDF" java
    __green "OK"
  else 
    __red "Error: Directory $JDF does not exists."
    exit 1
fi


# Update /etc/profile

declare profile="/etc/profile"
declare content="## JDK_ENV_START ##
JAVA_HOME=$JDK_LOCATION
PATH=$PATH:$JDK_LOCATION/bin
export JAVA_HOME
export PATH
## JDK_ENV_END ##"

file_content=$( < "${profile}" )
if [[ " $file_content " =~ $content ]] 
    then
        __yellow "JDK paths already sets in the $profile"
    else

echo -n "Updating /etc/profile ... "
cat >> /etc/profile <<EOF
$content
EOF
__green "OK"
fi

# Update system to use Oracle Java by default
echo -n "Updating system alternatives... "
{
update-alternatives --install "/usr/bin/java" "java" "$JDK_LOCATION/bin/java" 1
update-alternatives --install "/usr/bin/javac" "javac" "$JDK_LOCATION/bin/javac" 1
update-alternatives --install "/usr/bin/jps" "jps" "$JDK_LOCATION/bin/jps" 1
update-alternatives --set java "$JDK_LOCATION"/bin/java
update-alternatives --set javac "$JDK_LOCATION"/bin/javac
update-alternatives --set jps "$JDK_LOCATION"/bin/jps
} >> /dev/null 2>&1
__green "OK"

# Verify and exit installation
echo -n "Verifying Java installation... "
JAVA_CHECK=$(java -version 2>&1)
if [[ "$JAVA_CHECK" == *"Java(TM) SE Runtime Environment"* ]]; then
    __green "OK"
    echo
    __green "Java successfully installed!"
    echo
    java -version
    echo
    exit 0
else
    __red "FAILED"
    echo
    __red "Java installation failed!"
    echo
    exit 1
fi



