#!/bin/sh
#
# git prepare-commit-msg hook
# Sadly, on git merge, the pre-commit hook is not invoked. So we use
# this hook instead to check if a merge has borked cve syntax.
# Unfortunately, if the hook fails, then you are left in an incomplete
# merge state.
#

if ! [ "$1" = ".git/MERGE_MSG" ] ; then
    # this was not triggered by a git merge, so skip check (we do it
    # elsewhere for regular commits *and* it's handled more cleanly
    # there.
    exit 0
fi

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

# Redirect output to stderr.
exec 1>&2

cleanup() {
    if [ -n "${modified_files}" ] && [ -f "${modified_files}" ]  ; then
        rm "${modified_files}"
    fi
}

set -e

trap cleanup EXIT INT HUP

if [ -z "${UCT_IGNORE_CHECK_SYNTAX}" ] ; then
    modified_files="$(mktemp -t ucthook-XXXXXXXXXX)"
    # check-syntax needs full path to files so prepend it via sed
    dir=$(git rev-parse --show-toplevel)
    git diff --cached --name-only --diff-filter=AM $against | sed "s|^|${dir}/|" > "${modified_files}"

    if ! "${UCT}/scripts/check-syntax" --verbose --filelist "${modified_files}" ; then
        read -p 'Found syntax errors. Enter "ignore" to continue or anything else to exit: ' answer < /dev/tty
        if ! [ "${answer}" = "ignore" ] ; then
            echo 'Aborting, use git merge --abort to undo the merge action'
            exit 1
        fi
    fi
fi
