#!/bin/sh
#
# @author Michael Tucek <michael@tucek.eu>
# @brief Reformats Java source code
# @date 30.09.2021
# @tags reformat

FORMATTER_JAR=/opt/google-java-format.jar
GOOGLE_JAVA_FORMAT_VER=1.11.0
FORMATTER_DOWNLOAD_URL=https://github.com/google/google-java-format/releases/download/v${GOOGLE_JAVA_FORMAT_VER}/google-java-format-${GOOGLE_JAVA_FORMAT_VER}-all-deps.jar
if [ "$1" = "-d" ]; then
	if [ -f $FORMATTER_JAR ]; then
		echo "$FORMATTER_JAR already exists!"
	else
		echo "Downloading $FORMATTER_DOWNLOAD_URL to $FORMATTER_JAR"
		curl -o $FORMATTER_JAR -L $FORMATTER_DOWNLOAD_URL
	fi
	exit 0
fi

if [ -f $FORMATTER_JAR ]; then
	echo "Using existing $FORMATTER_JAR"
else
	echo "Formatter JAR not found in $FORMATTER_JAR"
	echo "Use switch -d to download $FORMATTER_DOWNLOAD_URL to $FORMATTER_JAR"
	exit 0
fi

SCRIPTS_DIR=$(dirname "$0")
. "${SCRIPTS_DIR}/include-common"

cd "$SOURCE" || {
	printf >&2 'Unable to change into source directory'
	exit 1
}

if [ $# -gt 0 ]; then
	source_files=$(printf "%s\n" "$@" | grep -x -E '.*\.java')
	if [ -z "$source_files" ]; then
		exit 0
	fi
else
	source_files=$(git ls-files '*.java')
fi

if [ -z "$JAVA" ]; then
	JAVA=$(command -v java)
fi

JDK_VERSION=$("$JAVA" --version | cut -d' ' -f2 | head -n1 | cut -d. -f1)

if [ "$JDK_VERSION" -lt "16" ]; then
	printf "%s\n" "$source_files" | sed -nE 's/(.*)/'"'"'\1'"'"'/p' | xargs "$JAVA" --illegal-access=permit -jar $FORMATTER_JAR --replace
else
	printf "%s\n" "$source_files" | sed -nE 's/(.*)/'"'"'\1'"'"'/p' | xargs "$JAVA" \
		--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \
		--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \
		--add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED \
		--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED \
		--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED \
		-jar $FORMATTER_JAR --replace
fi
