#!/bin/bash
set -e # fail fast

VERSION=$( [[ "$(grep "<version.google-java-format>" < "pom.xml")" =~ .*\>([^\<]+)\<.* ]] && echo "${BASH_REMATCH[1]}" )
[[ -z "$VERSION" ]] && echo "Could not find version. Aborting commit." && exit 1

REPOSITORY_URL="https://github.com/google/google-java-format/releases/download/v${VERSION}/"
JAR_NAME="google-java-format-${VERSION}-all-deps.jar"
JAR_DOWNLOAD_URL="$REPOSITORY_URL$JAR_NAME"

CACHE_DIR=".java-format-cache"

mkdir -p "$CACHE_DIR"
[[ ! -f "$CACHE_DIR/$JAR_NAME" ]] && curl -LJf "$JAR_DOWNLOAD_URL" -o "$CACHE_DIR/$JAR_NAME"

changed_java_files=$(git diff --cached --name-only --diff-filter=ACMR | grep ".*\.java$" | grep -v ".*Mapper.java$" || true)
if [ -n "$changed_java_files" ]
then
  java -jar "$CACHE_DIR/$JAR_NAME" --replace --skip-sorting-imports $changed_java_files;
  git add $changed_java_files;
fi
