#!/bin/bash

set -u

export scriptDir
scriptDir=$(dirname "$0")
basePath="$scriptDir/../../${1-.}"

if [ ! -d "$basePath" ]; then
  echo "Error, invalid path: $basePath"
  echo "Check script arguments"
  exit 1
fi

export green="\e[92m"
export blue="\e[34m"
export normal="\e[0m"
export bold="\e[1m"
export boldRed="${bold}\e[91m"

export javaFiles testFiles addedLines
javaFiles=$(mktemp)
testFiles=$(mktemp)
addedLines=$(mktemp)
trap 'rm $javaFiles $testFiles $addedLines' EXIT

## Create a cache of java and test files for faster iteration over all files.
find "$basePath" -type f -name "*.java" -path "*/src/main/java/*" > "$javaFiles"
find "$basePath" -type f -name "*Test.java" -path "*/src/test/java/*" > "$testFiles"

## Some checks have existing violations in the code base, so they only look at new code: the
## lines added to src/main/java since CHECK_BASE (default origin/main; CI sets the target branch),
## including uncommitted changes and new files, as "file:line:text".
checkBase="${CHECK_BASE:-origin/main}"
if ! mergeBase=$(git -C "$basePath" merge-base "$checkBase" HEAD 2> /dev/null); then
  echo "Error, cannot compare with '$checkBase'; set CHECK_BASE, eg: CHECK_BASE=upstream/main"
  exit 1
fi
git -C "$basePath" diff -U0 --no-color --no-ext-diff --relative --src-prefix=a/ --dst-prefix=b/ \
    "$mergeBase" -- ':(glob)**/src/main/java/**/*.java' \
  | awk '/^diff --git/ { inHunk = 0; next }
         /^\+\+\+ / && !inHunk { file = substr($0, 7); next }
         /^@@ / { inHunk = 1; split($3, start, ","); line = substr(start[1], 2); next }
         inHunk && /^\+/ { print file ":" line ":" substr($0, 2); line++ }' > "$addedLines"
git -C "$basePath" ls-files --others --exclude-standard -z -- ':(glob)**/src/main/java/**/*.java' \
  | (cd "$basePath" && xargs -0 grep -Hn '') >> "$addedLines"

status=0


function title() {
  echo -e "${bold}${blue}$1${normal}"
}
export -f title

function example() {
  echo -e "${blue}Ex: $1${normal}"
}
export -f example

function displayResult() {
  local found="$1"
  if [ "$found" -eq 0 ]; then
    echo -e "${green}[OK]${normal}"
  else
    echo -e "${boldRed}[FIX]${normal}"
  fi
  echo ""
}
export -f displayResult

# Prints the added lines whose text (not the "file:line:" part) matches the extended regex $1.
function grepAddedLines() {
  local -r pattern="$1"
  grep --color=auto -E "^[^:]+:[0-9]+:.*($pattern)" "$addedLines"
}
export -f grepAddedLines

# Joins the lines of a style.include file to one extended regex: "a|b|c" (also with CRLF).
function includePattern() {
  local -r file="$1"
  tr -d '\r' < "$scriptDir/style.include/$file" | paste -sd '|'
}
export -f includePattern

function favorJava9CollectionsApi() {
  title "Verifying preference to use List.of(), Map.of() and Set.of() compared to java.util.Collections.* (added lines)"
  example "instead of 'Collections.singleton(value)', use 'Set.of(value)', or EG: use 'Map.of(...)', or 'List.of(..)'"
  local found=0
  grepAddedLines "$(includePattern disallowed-collection-calls)" && status=1 && found=1

  displayResult "$found"
}
export -f favorJava9CollectionsApi

function referToCollectionsByInterfaceType() {
  title "Assign to collection types using their interface (added lines)"
  example "instead of 'ArrayList<String> list =', use 'List<String> list = '"
  local found=0
  grepAddedLines "$(includePattern concrete-collection-types)" && status=1 && found=1

  displayResult "$found"
}
export -f referToCollectionsByInterfaceType

function removeUnusedLogAnnotations() {
  title "Remove unused lombok @Slf4j annotations"
  local found=0

  while read -r file; do
    if grep --fixed-strings -q "@Slf4j" "$file"; then
      if ! grep -Eq "log::|log\." "$file"; then
        echo -e "${bold}$file${normal}"
        found=1
        status=1
      fi
    fi
  done <<< "$(cat "$javaFiles")"

  displayResult "$found"
}
export -f removeUnusedLogAnnotations

function preferSlf4jOverJavaLogging() {
  title "Use @Slf4j instead of @Log (added lines)"
  local found=0
  grepAddedLines "@Log\b|import java\.util\.logging\.Logger;" && status=1 && found=1

  displayResult "$found"
}
export -f preferSlf4jOverJavaLogging

function useEmptyOverSizeEqualsZero() {
  title "Avoid using size() to check for empty or not empty"
  example "size() == 0 -> isEmpty(), size() > 0 -> !isEmpty()"
  local found=0
  while read -r file; do
    grep --color=auto -EHn \
        "size\(\) == 0|size\(\) < 1|size\(\) <= 0|size\(\) > 0|size\(\) != 0|size\(\) >= 1" "$file" \
      && status=1 && found=1
  done <<< "$(cat "$javaFiles")"

  displayResult "$found"
}
export -f useEmptyOverSizeEqualsZero

# Checks for static imports by looking for fully qualified constructs used in test, eg:
#   Mockito.when
# We distinguish from imports and standard usages by looking for a trailing semicolon, eg:
#   import static ..MatcherAssert.assertThat;
# If we do not see that trailing semi-colon, then we have found something that is not statically
# imported.
function useStaticImportsInTest() {
  title "Use static imports in test"
  example "Mockito.when(..) -> when(..)"
  local found=0
  while read -r file; do
    grep --color=auto -EHn \
      "Mockito.when[^;]|Mockito.verify[^;|NoMoreInteractions;]|MatcherAssert.assertThat[^;]|Is\.is[^;]|IsInstanceOf\.instanceOf[^;]" \
      "$file" \
     && status=1 && found=1
  done <<< "$(cat "$testFiles")"
  displayResult "$found"
}
export -f useStaticImportsInTest

function useJavaxNonnullInsteadOfLombokNonNull() {
  title "Use javax.annotation.Nonnull instead of lombok.NonNull"
  local found=0
  while read -r file; do
    grep --color=auto --with-filename --line-number --fixed-strings \
      "lombok.NonNull" \
      "$file" \
     && status=1 && found=1
  done <<< "$(cat "$javaFiles")"

  displayResult "$found"
}
export -f useJavaxNonnullInsteadOfLombokNonNull

# .gitattributes stores text files with LF in git, even '*.bat' files checked out as CRLF.
# A file committed with CRLF anyway (eg: by a bot that writes through the GitHub API) shows
# as modified in every clone until it is renormalized.
function storeTextFilesWithLfLineEndings() {
  title "Store text files in git with LF line endings"
  example "git add --renormalize gradlew.bat"
  local found=0
  git -C "$basePath" ls-files --eol | grep -E "^i/(crlf|mixed) +[^ ]+ +attr/text" \
    && status=1 && found=1

  displayResult "$found"
}
export -f storeTextFilesWithLfLineEndings

# Relative links in the Markdown docs, like [text](../README.md#anchor), must point to an
# existing file or folder; '/' is the repository root. Web links and anchors are not checked.
function linkToExistingFilesInDocs() {
  title "Link to existing files in the docs"
  local found=0 root dir path
  root="$(git -C "$basePath" rev-parse --show-toplevel)"
  while IFS=: read -r file line target; do
    path="${target%%#*}"
    if [[ "$path" == /* ]]; then
      dir="$root"
    else
      dir="$basePath/$(dirname "$file")"
    fi
    [ -e "$dir/$path" ] || { echo "$file:$line: $target"; status=1; found=1; }
  done < <(git -C "$basePath" grep --line-number --only-matching \
      -E '\]\([^):#[:space:]][^):[:space:]]*\)' -- '*.md' | sed -E 's/\]\((.*)\)$/\1/')

  displayResult "$found"
}
export -f linkToExistingFilesInDocs

# Gradle projects are flat (settings.gradle.kts), so a path through the folders that hold them,
# like ':game-app:game-core', does not exist.
function useFlatGradleProjectPathsInDocs() {
  title "Use flat Gradle project paths in the docs"
  example "./gradlew :game-core:test, not ./gradlew :game-app:game-core:test"
  local found=0
  # the path must be an argument of the same command: no end of inline code or comment between
  git -C "$basePath" grep --line-number \
    -E 'gradlew[^`#]*[[:space:]]:?(game-app|http-clients|lib):' -- '*.md' \
    && status=1 && found=1

  displayResult "$found"
}
export -f useFlatGradleProjectPathsInDocs


removeUnusedLogAnnotations
useStaticImportsInTest
useJavaxNonnullInsteadOfLombokNonNull
storeTextFilesWithLfLineEndings
useEmptyOverSizeEqualsZero
linkToExistingFilesInDocs
useFlatGradleProjectPathsInDocs

## These have existing violations in the code base, so they check the added lines only
favorJava9CollectionsApi
referToCollectionsByInterfaceType
preferSlf4jOverJavaLogging

exit "$status"
