#!/usr/bin/env bash

# Installs JDK into environment
# Can only install OpenJDK versions
# --expire flag will skip installation if same JDK was installed less than 24 hours ago

set -uexo pipefail

script_home="$(cd "$(dirname "$0")" && pwd)"
cmdname="$(basename "$0")"

default=openjdk11

usage() {
    echo "Usage: $cmdname [--(no-)expire] <openjdk11|default|...> INSTALLDIR_IF_NEEDED"
}

misuse() { usage 1>&2; exit 2; }

jdk-info () { "$script_home"/jdk-info "$@"; }

epochsecs() { printf '%(%s)T\n' -1; }

expire=''

# Validate command arguments
while true; do
    case "$1" in
        --expire) expire='true'; shift ;;
        --no-expire) expire=''; shift ;;
        --) shift; break ;;
        *) break ;;
    esac
done

test $# -eq 2 || misuse
ver="$1"
install="$2"
# Path to the file this script uses to cache install time
install_time="$install/jdk/jdk-install-time"

# Version must be an OpenJDK version
case "$ver" in
    openjdk*) ;;
    default) ver="$default" ;;
    *)
        echo "$cmdname does not know how to install $ver" 2>&1
        exit 2
        ;;
esac

# If --expire flag is present, last JDK installation was within 24hrs, and the
# current JDK is the same as the one being requested, skip installation
if test "$expire"; then
    if test -e "$install_time"; then
        if test $(($(epochsecs) - $(< "$install_time"))) -lt 86400; then
            jdk_spec=$(JDK_INFO_JAVA="$install/jdk/bin/java" jdk-info --print spec)
            if test "$jdk_spec" = "$ver"; then
                # Don't update more than once per day
                exit 0
            fi
        fi
    fi
else  # not expiring
    if test openjdk"$(jdk-info --print spec)" = "$ver"; then
        exit 0
    fi
fi

# Create temporary directory
tmpdir="$(mktemp -d "$cmdname-XXXXXX")"
tmpdir="$(cd "$tmpdir" && pwd)"
trap "$(printf 'rm -rf %q' "$tmpdir")" EXIT

# Unsure OS is either Linux of MacOS
case "$OSTYPE" in
    linux*)
        adoptos=linux
        ;;
    darwin*)
        adoptos=mac
        ;;
    *)
        echo "Unexpected platform: $OSTYPE" 1>&2
        exit 2
        ;;
esac

# Get OpenJDK tarball from official source
curl -sSLo "$tmpdir/jdk.tar.gz" \
     -f --retry 3 \
     "https://api.adoptium.net/v3/binary/latest/${ver#openjdk}/ga/$adoptos/x64/jdk/hotspot/normal/eclipse?project=jdk"

# Extract OpenJDK from tarball
(cd "$tmpdir"
 mkdir tmp-unpack
 cd tmp-unpack
 tar xpSf ../jdk.tar.gz)

# Rename OpenJDK directory to "jdk"
case "$OSTYPE" in
    darwin*)
        (cd "$tmpdir/tmp-unpack"
         case "$ver" in
             openjdk10) mv * jdk ;;
             *) mv */Contents/Home jdk ;;  # At least 8 and 11
         esac)
        ;;
    *)
        (cd "$tmpdir/tmp-unpack" && mv * jdk)
        ;;
esac

# Remove current JDK if exists
rm -rf "$install/jdk"
mkdir -p "$install"
# Move new JDK to installation directory
mv "$tmpdir/tmp-unpack/jdk" "$install/jdk"
# Cache new JDK version
echo "$ver" > "$install/jdk/jdk-flavor"
# Cache current time as installation time
epochsecs > "$install_time"
