#!/bin/bash
set -e

# This Script is automatically added by the Gradle Plugin "dreipc.development"

filesToAddAfterFormatting=()
containsJavaOrKotlin=0

# Collect all files currently in staging area, and check if there are any java or kotlin files
for entry in $(git status --porcelain | sed -r 's/[ \t]+/-/g')
do

 if [[ $entry == M* ]] ; then
    # shellcheck disable=SC2206
    filesToAddAfterFormatting+=(${entry:2}) # strips the prefix
 fi

 if [[ $entry == *.java ]] || [[ $entry == *.kt ]] ; then
    containsJavaOrKotlin=1
 fi
done;


# If any java or kotlin files are found, run spotlessApply
if [ "$containsJavaOrKotlin" == "1" ] ; then
  echo "*****Kotlin and/or Java found in staging, running:  ./gradlew -PdisableSpotlessCheck spotlessApply *****"
  ./gradlew spotlessApply
else
  echo "Not running spotlessApply"
fi

# Add the files that were in the staging area
# shellcheck disable=SC2128
for fileToAdd in $filesToAddAfterFormatting
do
  echo "***** re-adding $fileToAdd after formatting *****"
  git add "$fileToAdd"
done;

echo "*****Running unit tests: ./gradlew test******"
./gradlew test