#!/usr/bin/env bash

set -eo pipefail

function format_and_sort() {
  # Run the validate and import check commands, suppressing all output and errors
  if ! mvn formatter:validate impsort:check whitespace:veirfy xml-format:xml-check > /dev/null 2>&1; then
    # If validation failed, fix it by ensuring code is formatted correctly
    # and that imports are sorted as some IDEs automatically change it on save
    mvn formatter:format impsort:sort

    # Fail the commit, so the author can re-select what to commit
    echo "Formatting and/or import sorting were required. Please check and make another commit."
    exit 1
  fi

  # If no error occurred, print a success message
  echo "All files are properly formatted and imports are sorted."
}

format_and_sort