#!/bin/sh
#
# This pre-commit hook checks if any versions of clang-format
# are installed, and if so, uses the installed version to format
# the staged changes.

base=clang-format-10
format=""
yapf_base=yapf
yapf_format=""

use_yapf=true

# Redirect output to stderr.
exec 1>&2

# check if clang-format is installed
type "$base" >/dev/null 2>&1 && format="$base"

# no versions of clang-format are installed
if [ -z "$format" ]
then
    echo "$base is not installed. Pre-commit hook will not be executed."
    exit 0
fi

# check if yapf is installed
type "$yapf_base" >/dev/null 2>&1 && yapf_format="$yapf_base"

# no versions of yapf are installed
if [ -z "$yapf_format" ]
then
    echo "$yapf_base is not installed. Pre-commit hook for python files will not be executed"
    use_yapf=false
fi

# Do everything from top - level
cd $(git rev-parse --show-toplevel)

if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=16bbb57
fi

# do the formatting
for file in $(git diff-index --cached --name-only $against | grep -E '\.h$|\.hpp$|\.cpp$|\.cl$|\.h\.in$|\.hpp\.in$|\.cpp\.in$|\.py$')
do
    if [ -e "$file" ]
    then
        if [ $(echo $file | grep -E '\.py$') ]
        then
            if $use_yapf
            then
                echo "$yapf_format $file"
                "$yapf_format" -i "$file"
            fi
        else
            echo "$format $file"
            "$format" -i -style=file "$file"
        fi
    fi
done
