#!/bin/bash

OS_ALLCAPS=`uname -s | sed 's/_.*$//' | tr 'a-z' 'A-Z'`

########################## CONSTANTS ########################
# Expected JDK major versions for Greenstone and Expeditee
GS_VER=11
#EXP_VER=17fx
EXP_VER=11fx

# Specific full version number possibilities for above
################
# IMPORTANT:
# When changing the version of JDK, make sure there is a self-extracting JRE updated to a matching version
# in the release-kit at https://trac.greenstone.org/browser/main/trunk/release-kits/shared/OS
################
#JDK11=11.88.17-ca-jdk11.0.31
JDK11=11.82.19-ca-jdk11.0.28

## Expeditee needs JDK with FX
################
## IMPORTANT: if you update the JDK version used by expeditee,
## also edit the version referred to in https://trac.greenstone.org/browser/other-projects/expeditee-release-kits/trunk/kits/rke/installer/build.xml
## For now jdkversion-settings.sh|bat produced by this script isn't a
## properties file yet, because bat files that set the env aren't properties
## files. So rke-setup.sh can't source jdkversion-settings.bat, the way it could
## source jdkversion-settings.sh. We'll need to think on that.
##################
JDK11_FX_64=11.86.21-ca-fx-jdk11.0.30
# We're not using JDK v17 for now
JDK17_FX_64=17.64.17-ca-fx-jdk17.0.18

# The full JDK version number combinations allowed for Greenstone and Expeditee
# Unless -f (fullver) is provided to specify the JDK requested (it needs to exist in trac)
GS_JDK=$JDK11
#EXP_JDK_FX=$JDK17_FX_64
EXP_JDK_FX=$JDK11_FX_64

# IF WE MOVE TO APPLE SILICON MACs, NEED UPDATES. Per Gemini:
# The Architecture Pitfall: getconf LONG_BIT
# On modern macOS, getconf LONG_BIT will return 64, which is perfect. Your script will fall back to bit=64 automatically.
# The Catch: Your script assumes that a 64-bit architecture means it should download the 64-bit Linux/Windows style JDK bundles (JDK11_64, JDK11_FX_64, etc.).
#
# *    Apple Silicon Macs (M1/M2/M3/M4): These run on an arm64 (AArch64) architecture. If your SVN repository (trac) hosts standard x86_64 (Intel) JDK binaries, they will technically run on Apple Silicon via macOS's built-in Rosetta 2 translation layer. However, native performance would require an ARM64 JDK bundle.
# *    If your downstream PREPARE-DARWIN.sh script specifically downloads an Intel JDK, it will function, but you may want to ensure your upstream repo accounts for Apple Silicon if maximum performance is needed.
#
# Recommendations to Ensure Success
# Rosetta 2: If your Mac users are on Apple Silicon and your PREPARE-DARWIN.sh pulls down an Intel (x64) JDK, ensure Rosetta 2 is installed on their machines by checking if they can run x64 applications.

######################## END CONSTANTS #########################

# This script will be creating a file called jdkversion-settings.sh so it can get sourced
# It will contain 3 variables: (JDK) majorversion, fullversion and bitness

# Fallback defaults
# if no commandline parameter gives us the bitness, determine the bitness for this machine
bit=`getconf LONG_BIT` # returns 32 or 64
# JDK 11 for greenstone and JDK 17 for expeditee by default
ver=$GS_VER
# fullversion will be set eventually based on defaults, unless provided
fullversion=

usage() {
    echo ""
    echo "Run as follows:"
    echo "  $0 [-v majorversion | -f fullversion] [-b 32|64]"
    echo ""
    echo "- Suffix 'fx' to majorversion number to get the specified JDK with FX."
    echo "- By default (no args) gets plain JDK 11 for this machine's bitness."
    echo ""
    echo "e.g. $0 -v 11 -b 64"
    echo "     will get the 64 bit JDK 11."
    echo "e.g. $0 -v 11fx"
    echo "     will get JDK 11 with FX if available for this machine's bitness."
    echo "e.g. $0 -f $JDK17_FX_64"
    echo "     will get JDK 17 with FX if available for this machine's bitness."
    echo ""
}

# https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script
# Googled also: getopts compulsory parameters
# on how to enforce compulsory parameters
while getopts :hv:b:f: flag
do
    case "${flag}" in
        h) usage; exit -1 ;;
        v) ver=${OPTARG};;
        b) bit=${OPTARG};;
	f) fullversion=${OPTARG};;
        :) echo "Error: -$OPTARG requires an argument." >&2; usage; exit 1 ;;        
        \?) echo "Error: Unknown option -$OPTARG" >&2; usage; exit 1 ;;
    esac
done

# If bitness is passed in, use that iff sensible
if [ "$bit" != "32" ] && [ "$bit" != "64" ]; then
    echo "Bitness -b has to be 32 or 64"
    usage
    exit 1
fi

# if fullver passed in, fullversion=fullver and determine ver from that
if [ -n "$fullversion" ] ; then
    # major version, $ver, is everything before first period mark (code from chatbot)
    ver=${fullversion%%.*}
    echo "Requested JDK version $fullversion (major version $ver) for bitness $bit"
    echo "The zip for this will need to exist in trac or we'll try to download it."
else
    # set pre-determined fullversion number based on $ver and $bit
    # which may have been passed in or are the default fallbacks
    if [ "$ver" = "$GS_VER" ] ; then
        fullversion="$GS_JDK"
    elif [ "$ver" = "$EXP_VER" ]; then
	# clear the 'fx' suffix from the version passed in (and any chars after)
	# https://superuser.com/questions/1005796/bash-string-manipulation-get-string-before-or-after-substring
	fx="fx"
	ver=${ver%$fx*}
	
	if [ "$bit" = "32" ]; then
	    echo "No support (yet) for 32 bit JDK${EXP_VER} as we currently generate Expeditee for 64 bit machines."
	    usage
	    exit 1
	else
	    fullversion="$EXP_JDK_FX"
	fi
    else
	echo "Unsupported Java version $ver requested."
	echo "Should be JDK version $GS_VER for Greenstone or $EXP_VER for Expeditee"
	usage
	exit 1
    fi
fi

# Don't really need to shift the arguments as we're not passing them onto any other scripts
# Now handle positional arguments (shifts remaining parameters to start at 1st position)
# https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script
# This will also update $* (and $# and $@) to deal with just the positional arguments
shift $((OPTIND - 1))

echo "v: $ver; b: $bit, f: $fullversion"
echo "Remaining args: $*"
if [ "$OS_ALLCAPS" = "DARWIN" ] && [ "$bit" = "32" ]; then
    echo "   Mac long ago dropped all support for 32 bit applications, including 32 bit JDK."
    echo "   Ensure you pass in -b 64 or don't pass in this flag and value at all."
    exit 1
fi
#echo "Prematurely exiting for testing"
#exit 0


cli_svn_root=https://svn.greenstone.org/main/trunk/cli-extensions

# Trac URL will have no bitness, it will just be selfcontained-jdk
# Only when selfcontained-jdk is checked out will it be
# checked out with bitness suffixed as "selfcontained-jdk<32|64>"
trac_selfcon_ext=selfcontained-jdk
selfcon_ext=$trac_selfcon_ext${bit}

installed_dir=${selfcon_ext}/zulu-jdk${ver}-${bit}bit

echo ""
if [ ! -d $selfcon_ext ] ; then
    echo "Checking out from svn: Greenstone3's $trac_selfcon_ext extension"
    svn co $cli_svn_root/$trac_selfcon_ext/source $selfcon_ext

    if [ $? != 0 ] ; then
	echo "Error encountered checking out: " 1>&2
	echo "    svn co $cli_svn_root/$trac_selfcon_ext/source $selfcon_ext" 1>&2
	exit 1
    fi
else
    echo "Detected directory '$selfcon_ext'"
    echo "=> Taken to mean that the svn check-out command has already been run"
fi

# Now that we've checked that selfcon_ext folder exists
echo "# File auto-generated by get-selfcontained-jdk.sh" > $selfcon_ext/jdkversion-settings.sh
echo ""
echo "majorversion=$ver" >> $selfcon_ext/jdkversion-settings.sh
echo "bitness=$bit" >> $selfcon_ext/jdkversion-settings.sh
echo "fullversion=$fullversion" >> $selfcon_ext/jdkversion-settings.sh
echo ""
#echo "Prematurely exiting for testing"
#exit 0

echo ""

thisOS=`uname -s`
thisOS=$(echo "$thisOS" | tr '[:upper:]' '[:lower:]')
filesuffix=_x64
if [ "$bitness" = "32" ]; then
    filesuffix=_i686
fi
osfname=$thisOS
if [ "$thisOS" = "darwin" ] ; then
    osfname=macosx
fi
# e.g. zulu11.82.19-ca-jdk11.0.28-macosx_x64.tar.gz
jdk_fname=zulu${fullversion}-${osfname}${filesuffix}

# If we don't have the version specified already downloaded
# we first get rid of anything we have previously downloaded
# and PREPARE-<OS>.sh will take care of the rest
if [ ! -e $selfcon_ext/${jdk_fname}.tar.gz ] ; then
    echo "@@@ Different JDK version requested: ${jdk_fname}.tar.gz. Doesn't match existing in $selfcon_ext"
    echo "    Deleting existing..."
    # If any other version of tarball exists, delete it
    # If any other zulu jdk folder exists, delete it too
    
    # This will mean $installed_dir doesn't exist and will trigger PREPARE-LINUX.sh below
    # It will also ensure a new tarball is obtained instead of extracting the existing tarball.
    rm -rf $selfcon_ext/zulu*        
fi

if [ ! -d $installed_dir ] ; then
    # PREPARE-${OS_ALLCAPS}.sh (PREPARE-DARWIN|LINUX.sh) has been merged as PREPARE-UNIX.sh
    echo "Running the $selfcon_ext/PREPARE-UNIX.sh"

    cd $selfcon_ext && ./PREPARE-UNIX.sh

    if [ $? != 0 ] ; then
	echo "Error encountered running: " 1>&2
	echo "        cd $selfcon_ext && ./PREPARE-UNIX.sh" 1>&2
	exit 1
    fi
	
else
    echo "Detected directory '$installed_dir'"
    echo "=> Taken to mean that the $selfcon_ext/PREPARE-UNIX.sh command has already been run"    
fi


if [ "x$JAVA_HOME" != "x$PWD/$installed_dir" ] ; then
    echo ""
    echo "To use this installed version of JDK, run "
    echo "    source ./SETUP-CLI.sh "
    echo "in the ext-cli folder."
    echo ""
else
    echo ""
    echo "Detected JAVA_HOME set to \$PWD/$installed_dir"
    echo "=> Taken to mean that the $selfcon_ext SETUP.sh file has been sourced"
fi

echo ""
