#!/usr/bin/env bash

# Copyright (C) Lightbend Inc. <https://www.lightbend.com>

# Lib for CI scripts

set -e
set -o pipefail

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
BASEDIR=$DIR/..
export DOCUMENTATION=$BASEDIR/documentation

printMessage() {
  echo "[info]"
  echo "[info] ---- $1"
  echo "[info]"
}

runSbt() {
  sbt -jvm-opts "$BASEDIR/.travis-jvmopts" 'set concurrentRestrictions in Global += Tags.limitAll(1)' "$@" | grep --line-buffered -v 'Resolving \|Generating '
}

# Runs code formating validation in the current directory
scalafmtValidation() {
  printMessage "VALIDATE SCALA CODE FORMATTING"
  runSbt +scalafmtCheckAll scalafmtSbtCheck || (
    echo "[error] ERROR: Scalafmt test failed for $1 source."
    echo "[error] To fix, format your sources using 'sbt scalafmtAll scalafmtSbt' before submitting a pull request."
    false
  )
}

# Runs code formating validation in the current directory
javafmtValidation() {
  printMessage "VALIDATE JAVA CODE FORMATTING"
  setJavafmtIntegrationTests "$1"
  runSbt javafmt test:javafmt $JAVAFMT_INTEGRATION_TESTS
  git diff --exit-code || (
    echo "[error] ERROR: javafmt check failed for $1 source, see differences above."
    echo "[error] To fix, format your sources using 'sbt javafmt test:javafmt' before submitting a pull request."
    false
  )
}

setJavafmtIntegrationTests() {
  JAVAFMT_INTEGRATION_TESTS=""
  if [ "$1" == "framework" ]; then
      JAVAFMT_INTEGRATION_TESTS="it:javafmt"
  fi
}
