#!/bin/bash

# Script to add all new JDK versions into selfcontained-jdk and
# update the JREs used by GS or expeditee release-builders to match.
# You'll still need to update the JDK version var in ext-cli/get-selfcontained-jdk
# This script is to be run from a linux machine
# that has been given the permissions to commit large files (>=100Mb)

fullversion=

# zulu URL prefix
download_url_prefix="https://cdn.azul.com/zulu/bin/"
selfcon_jdk=selfcontained-jdk

usage() {
    echo ""
    echo "**********************************************************"
    echo "This script will attempt to download JDKs of the version"
    echo "indicated into cli-extensions/selfcontained-jdk/downloads"
    echo "and matching JREs into (expeditee-)release-kits/shared/<OS>"
    echo ""
    echo "WARNING: This script is only to be run from a linux machine"
    echo "that has been given the permissions to commit large files"
    echo "**********************************************************"
    echo "Run as follows:"
    echo "  $0 <fullversion> [greenstone (default)|expeditee]"
    echo ""
    echo "This script downloads and svn commits to cli-extensions the specified JDK"
    echo "   and svn commits to release-kits/shared/OS(/wrapper) the matching JRE"
    echo "   for all release OS: mac (64), windows 32 and 64, linux 32 and 64."
    echo ""
    echo "   e.g. $0 11.82.19-ca-jdk11.0.28"
    echo "Or for JDK with fx for expeditee:"
    echo "   e.g. $0 11.86.21-ca-fx-jdk11.0.30 expeditee"
    echo ""
}

# download the hava archives locally, then move into selfcontained-jdk64/downloads
# and svn add, ready to commit
download_and_svn_add_jdk() {
	java_fname=$1
	
	java_url=${download_url_prefix}${java_fname}
	svn_file_url="https://svn.greenstone.org/main/trunk/cli-extensions/selfcontained-jdk/downloads/${java_fname}"

	# Any existing contents on SVN need to be replaced with fresh version,
	# shouldn't bail if the JDK is already on SVN, comment out this if-else block
	if svn info "$svn_file_url" > /dev/null 2>&1 ; then
	    echo "@@@ Not downloading nor svn adding file $java_fname"
	    echo "    The same version already exists at $svn_file_url"
	    return 1
	else
	    echo "JDK $java_fname not on SVN. Downloading from $java_url"
	fi
	
	# Check if we've already downloaded for this OS-bitness in a previous attempt
	if [ -e ${java_fname} ] ; then
		echo "$java_fname already exists in cli-extensions, will not download."
	else
	    # Download from zulu after testing the URL exists
	    # if [[ `wget -S --spider $java_url  2>&1 | grep 'HTTP/1.1 200 OK'` ]]; then
	    if curl --output /dev/null --silent --head --fail "$java_url"; then
		#echo "URL exists: $java_url"
		#wget --no-check-certificate $java_url
		curl $java_url > ${java_fname}
	    else
		echo "### ERROR: Can't download. URL does not exist: $java_url"
	    fi
	fi
	
	if [ -e ${java_fname} ] ; then	    
	    
	    if [ ! -e ${selfcon_jdk}/downloads/${java_fname} ] ; then
		mv ${java_fname} ${selfcon_jdk}/downloads/.

		#svn add ${selfcon_jdk}/downloads/${java_fname}
		##svn commit -m "Committing requested JDK $fullversion not already on trac" $selfcon_ext/${java_fname}
		
		# If jdk version exists on SVN already, don't svn add it but
		# allow overwriting it with version newly downloaded from zulu above
		if svn info "$svn_file_url" > /dev/null 2>&1 ; then
		    echo "@@@ Not svn adding file $java_fname"
		    echo "    The same version already exists at $svn_file_url"
		else
		    echo "JDK $java_fname not on SVN. Doing the svn add step"
		    svn add ${selfcon_jdk}/downloads/${java_fname}		    
		fi
	    else
		mv ${java_fname} ${selfcon_jdk}/downloads/.
	    fi
	else
	    echo "ERROR: Could not download java from $java_url"
	    exit 1
	fi
}

# Function downloads a JRE tarball/zip file and adds it to svn. Will commit all JREs later
download_and_svn_add_jre() {
    # jre_file looks like zulu11.82.19-ca-jre11.0.28
    # os is mac|win|linux
    jre_file=$1
    os=$2
    bitness=$3    
    svn_url_file_prefix=$4
    
    if [[ "$bitness" == "64" ]] ; then
	bit_download_suffix="_x64"
    else
	bit_download_suffix="_i686"
    fi

    #jre_file=zulu${jre_version} # prefix
    
    # Will build up to URL like
    # https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-linux_x64.tar.gz
    # https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-linux_i686.tar.gz
    # curl https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-macosx_x64.tar.gz
    
    if [ "$os" == "windows" ] ; then
        # https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-win_x64.zip
	# https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-win_i686.zip
        jre_file=${jre_file}-win${bit_download_suffix}.zip
    elif [[ "$os" == "mac" ]] ; then
	# https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-macosx_x64.tar.gz 
        jre_file=${jre_file}-macosx${bit_download_suffix}.tar.gz
    else 
        # https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-linux_x64.tar.gz
	# https://cdn.azul.com/zulu/bin/zulu11.82.19-ca-jre11.0.28-linux_i686.tar.gz
        jre_file=${jre_file}-linux${bit_download_suffix}.tar.gz
    fi
    
    jre_url=${download_url_prefix}${jre_file}
    echo "    File   : $jre_file"
    echo "    URL    : $jre_url"                

    # If we're testing this script, we may have downloaded the JRE from zulu already
    # don't keep downloading from there
    if [ -e $jre_file ] ; then
	echo "@@@ JRE file already exists locally: $jre_file. Not downloading."
    else
	# Download from zulu
	# Test the URL exists before attempting to download:
	# e.g. what if the user provided a nonsensical value for parameter fullversion?
	# if [[ `wget -S --spider $jre_url  2>&1 | grep 'HTTP/1.1 200 OK'` ]]; then
	if curl --output /dev/null --silent --head --fail "$jre_url"; then
	    #echo "URL exists: $jre_url"
	    #wget --no-check-certificate $jre_url
	    curl $jre_url > $jre_file	    
	else
	    echo "### ERROR: Can't download. URL does not exist: $jre_url"
	    return 1
	fi
    fi

    if [ -e $jre_file ] ; then
	#if svn info ^$file_url > /dev/null 2>&1 ; then
	svn_file_url=$svn_url_file_prefix/${jre_file}
	if svn info "$svn_file_url" > /dev/null 2>&1 ; then
	    echo "@@@ Not svn adding file $jre_file"
	    echo "    already exists at $svn_file_url"
	else
	    echo "JRE $jre_file not on SVN. Doing the svn add step"
	    #echo "JRE not on SVN, will get from official site (Zulu)"
	    # Do the wget/curl downloading here?
	    svn add $jre_file
	fi
    fi
}


# Command line param processing
if [ -z "$1" ] ; then
	echo "No parameters provided!"
	usage
	exit 1
else
    fullversion=$1
fi

# By default assume greenstone, not expeditee
app=greenstone
if [ -n "$2" ] ; then
    app=$2
fi
echo "*****************************************"
echo "Running script $0 for application: $app"
echo "*****************************************"


# Download and svn add (if not already on trac) all JDKs for the given fullversion
# But if the fullversion specified only jre, then don't grab the JDKs
if [[ "$fullversion" == *"jre"* ]]; then
    echo "NOTE: jre mentioned in $fullversion. Assuming you meant jdk too."
    find="jre"
    replace="jdk"
    fullversion=${fullversion//$find/$replace}
    # Change 11.82.19-ca-jre11.0.28 to 11.82.19-ca-jdk11.0.28
    java_fileprefix=zulu${fullversion}
    echo "         Corrected to $fullversion."
fi
##if [[ "$fullversion" == *"jre"* ]]; then
    ##echo "WARNING: Only JRE requested as seen in mention of jre in $fullversion."
    ##echo "         Won't download and commit any JDKs, only JREs."
##else

# Check out just the empty subdirectory structure we're going to commit to
if [ ! -d ${selfcon_jdk} ] ; then
    svn up --set-depth=empty ${selfcon_jdk}
    if [ ! -d ${selfcon_jdk}/downloads ] ; then
	svn up --set-depth=empty ${selfcon_jdk}/downloads
    fi
fi

java_fileprefix=zulu${fullversion}

# Process each of the java archives for all OS locally:
# first check if the file is not already locally downloaded
# then download it from zulu and move each file
# into ${selfcon_jdk}/downloads readh to commit
download_and_svn_add_jdk "${java_fileprefix}-macosx_x64.tar.gz"
download_and_svn_add_jdk "${java_fileprefix}-win_x64.zip"
download_and_svn_add_jdk "${java_fileprefix}-linux_x64.tar.gz"
download_and_svn_add_jdk "${java_fileprefix}-win_i686.zip"
download_and_svn_add_jdk "${java_fileprefix}-linux_i686.tar.gz"

# Can only commit these JDK file from machines that have been given
# special permissions to commit files as large as these JDK tarballs
# Commit all the java archives which should now all be in ${selfcon_jdk}/downloads
pushd ${selfcon_jdk}/downloads/.
svn commit -m "AUTOCOMMIT of requested JDKs version $fullversion for the various release OS" .
popd    
##fi

# Next, download and svn add the JREs for this new JDK version to release-kits/shared/<OS>/

# $fullversion will look like 11.82.19-ca-jdk11.0.28
# want to turn it into JRE version: 11.82.19-ca-jre11.0.28
#https://stackoverflow.com/questions/3306007/replace-a-string-in-shell-script-using-a-variable
find="jdk"
replace="jre"
jre_version=${fullversion//$find/$replace}
# This will build string up to full jre version info like 11.82.19-ca-jre11.0.28
jre_fileprefix=zulu${jre_version}


# Using arrays in bash like I did earlier
# at https://trac.greenstone.org/browser/other-projects/gti/translation_status.sh
svn_prefix="https://svn.greenstone.org/main/trunk/release-kits/shared/"
if [[ "$app" == "expeditee" ]]; then
    echo "@@@ Running this script for expeditee. Will commit JREs to expeditee-release-kits"
    svn_prefix="https://svn.greenstone.org/other-projects/expeditee-release-kits/trunk/shared/"
    exit
fi

# For greenstone or expeditee, the following are the sub folders of
# their release-kits/shared folder checkout in which the self-extracting
# jre is to exist, so let's download and svn add the new JRE there
svn_folders=("windows" "linux" "mac")

all_suffix_folders=""

echo ""
echo "### Going to try downloading JRE:"
echo "    Version: $jre_fileprefix"
echo ""

# To zip up folder on Win 10/11: tar -caf archive.name.zip folder_name
for os in ${svn_folders[@]}; do

    if [ ! -d "$os" ]; then
	echo "Checking out the app's release-kits/shared/$os"
	svn co --depth empty $svn_prefix$os
    fi    

    if [ ! -d "$os" ]; then
	echo "### ERROR: Could not svn checkout directory $svn_prefix$os"
	echo "Can't download and commit the JRE tarball/zip into it"
	continue
    fi

    echo "@@@ About to pushd into folder $os"
    pushd "$os"
    
    # check if a jre tarball by this name already exists, as svn add won't work if it exists
    svn_url_file_prefix=${svn_prefix}${os}

    download_and_svn_add_jre $jre_fileprefix $os "64" "$svn_url_file_prefix"
    # For windows and linux also download the 32 bit version
    if [[ "$os" != "mac" ]] ; then
	echo ""
	download_and_svn_add_jre $jre_fileprefix $os "32" "$svn_url_file_prefix"
    fi

    echo "@@@ About to leave folder $os"
    popd # get out of wrapper/linux/mac folder

    all_suffix_folders="$all_suffix_folders $os"
    echo ""
done

# now $all_suffix_folders=wrapper linux mac
# Can commit the changes in all 3 folders
svn commit -m "AUTOCOMMIT of requested JRE version $fullversion for all release OS-es" $all_suffix_folders


echo ""
echo "**********************************************************"
echo "BREADCRUMBS:"
echo "You must next update the java version variable JDK11 in the"
echo "following 2 files to the new version: ${fullversion}"
echo "   https://trac.greenstone.org/browser/main/trunk/ext-cli/get-selfcontained-jdk.sh"
echo "   https://trac.greenstone.org/browser/main/trunk/ext-cli/get-selfcontained-jdk.bat"
echo "**********************************************************"
echo ""

