#!/usr/bin/env bash

#
# Pre-commit hook for git.
#


# Only run when on a branch (to avoid rebase confusion)
#
# NOTE: copy-pasted; not sure if necessary
git symbolic-ref --short -q HEAD > /dev/null || exit 0

if git-rev-parse --verify HEAD &> /dev/null; then
  against=HEAD
else
  # Initial commit: diff against an empty tree object
  against=$(git hash-object -t tree /dev/null)
fi

error=0
pids=()

# Loop over (A)dded (C)opied or (M)odified text files and output all
# files with syntax errors, not just the first.
#
# Use background processes to parallelise the checks.
for file in $(
  git diff-index --cached --name-only --diff-filter=ACM $against -z |
  xargs -0 file --mime |
  awk -F":[ ]*" '$2 ~ /^text/ {print $1}'
); do
  (
    err=0
    tmpfile="$(dirname "$file")/sinter.$$.$(basename "$file")"
    git show ":$file" > "$tmpfile"
    sinter -q "$tmpfile"

    # ignore exit code 2 (no linter for file)
    if [ $? -eq 1 ]; then
      err=1
      echo syntax error in "$file"
    fi

    rm "$tmpfile"
    exit $err
  ) & pids+=($!)
done

for pid in ${pids[*]}; do
  if ! wait $pid; then
    error=1
  fi
done

exit $error
