#!/bin/bash

# Regexp for grep to only choose some file extensions for formatting
exts="\.\(cpp\|h\)$"

# The formatter to use
formatter=`which uncrustify`

# Check availability of the formatter
if [ -z "$formatter" ]
then
  1>&2 echo "$formatter not found. Pre-commit formatting will not be done."
  exit 0
fi

# Format staged files
for file in `git diff --cached --name-only --diff-filter=ACMR | grep $exts`
do
  echo "Formatting $file"
  # get tmpfile
  tmpfile="${file//.cpp/.tmp.cpp}"
  tmpfile="${tmpfile//.h/.tmp.h}"
  # Get the file from index
  git show ":$file" > "$tmpfile"
  # Format it
  "$formatter" --no-backup -c AfRApay.MateCard/.uncrustify.cfg "$tmpfile"
  # Format the non-tmp file too, to prevent loops
  "$formatter" --no-backup -c AfRApay.MateCard/.uncrustify.cfg "$file"
  # Create a blob object from the formatted file
  hash=`git hash-object -w "$tmpfile"`
  # Add it back to index
  git update-index --add --cacheinfo 100644 "$hash" "$file"
  # Remove the tmp file
  rm "$tmpfile"
done

# If amend - force succeed
IS_AMEND=$(ps -ocommand= -p $PPID | grep -e '--amend');
if [ -n "$IS_AMEND" ]; then
  exit 0
fi

# If no files left in index after formatting - fail
ret=0
if [ ! "`git diff --cached --name-only`" ]; then
  1>&2 echo "No files left after formatting"
  exit 1
fi
