#!/bin/dash
# getjava
# jamesbond 2015, 2019
# JakeSFR 2018
# MIT license

VERSION=${VERSION:-8}

WORKDIR=/tmp/getjava/work.$$
#COMP_MODE="-comp lzo -Xcompression-level 1"
COMP_MODE=${COMP_MODE:-"-comp xz -Xbcj x86"}

setarch() {
	SYSARCH=$(uname -m)
	[ $VERSION -ge 11 ] && SYSARCH='x86_64'	# version 11 is x64 only!

	case $SYSARCH in
		x86_64)
			ARCH=x64
			ARCH_REGEX='(x64|x64_bin)'	# x64_bin is for version 11
			LIBDIR=lib64
			LIBPATH=amd64
			;;
		i?86)
			ARCH=i586
			ARCH_REGEX=i586
			LIBDIR=lib
			LIBPATH=i386
			;;
		*) msg "Unsupported architecture."
		   exit 1 ;;
	esac
}

# $@ - text
msg() {
	echo "$@"
}

# Based on https://gist.github.com/n0ts/40dd9bd45578556f93e7
download() {
	msg "Searching for the latest version of JDK ${VERSION} ..."
	
	MAIN_URL="https://www.oracle.com"
	JDK_URL="${MAIN_URL}/technetwork/java/javase/downloads/index.html"

	DL_URL=$(
		curl -L -s $JDK_URL | \
		egrep -o "\/technetwork\/java/\javase\/downloads\/jdk${VERSION}-downloads-.+?\.html" | \
		head -1 | \
		cut -d '"' -f 1
	)
	
	if [ -z "$DL_URL" ]; then
		msg "Could not get JDK download URL."
		exit 1
	fi

	DL_URL=${MAIN_URL}${DL_URL}

	DL_URL=$(
		curl -L -s $DL_URL | \
		egrep -o "(http|https)\:\/\/download.oracle\.com\/otn-pub\/java\/jdk\/([1-9][\.u0-9]*)(\+|\-)[b0-9]*\/[a-f0-9]+\/jdk-\2(-|_)linux-${ARCH_REGEX}.tar.gz" | \
		sort -r | head -n 1
	)

	# used in makesfs()
	FULL_VERSION=$(echo ${DL_URL##*/} | cut -f2 -d '-' | cut -f1 -d '_')

	msg "Downloading ${DL_URL##*/} ..."

	#curl -C - -LR#OH "Cookie: oraclelicense=accept-securebackup-cookie" -k $DL_URL
	curl -C - -LR#O --cookie "oraclelicense=accept-securebackup-cookie" -k $DL_URL
}

makesfs() {
	msg "Converting to SFS ..."

	cd $WORKDIR &&
	mkdir -p workroot && cd workroot &&
	tar -xf ../jdk* && rm -f ../jdk* &&

	mkdir -p ./opt ./usr/bin &&
	mv ./jdk* ./opt/java-$FULL_VERSION &&
	ln -sf java-$FULL_VERSION ./opt/java &&
	
	# create binary symlinks
	for p in jar jarsigner java javac javadoc javah javap javaws jconsole jvisualvm policytool keytool; do
		[ -e ./opt/java/bin/$p ] && ln -sf /opt/java/bin/$p ./usr/bin/$p
	done && 
	
	# v11 doesn't have this one
	if [ $VERSION -lt 11 ]; then
		mkdir -p ./usr/$LIBDIR/mozilla/plugins
		ln -sf /opt/java/jre/lib/$LIBPATH/libnpjp2.so ./usr/$LIBDIR/mozilla/plugins/libnpjp2.so
	fi

	# v12 has super ugly font, fix it
	if [ $VERSION -ge 12 ]; then
		mkdir -p ./etc/profile.d &&
cat > ./etc/profile.d/java.sh << "EOF" &&
export _JAVA_OPTIONS='-Dawt.useSystemAAFontSettings=on'
EOF
		chmod +x ./etc/profile.d/java.sh || return 1
	fi
	
	cd .. &&
	mksquashfs workroot $HOME/java-jdk-$FULL_VERSION-$ARCH.sfs -noappend $COMP_MODE &&
	rm -rf workroot

}

trap '[ -e $WORKDIR ] && cd $WORKDIR && cd .. && rm -rf $WORKDIR; exit' INT HUP 0

### main
setarch
mkdir -p $WORKDIR; cd $WORKDIR
download
makesfs
msg "Done - SFS saved to $HOME"
