#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

SUBPROJECTS=subprojects

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
    if [ -n "${modified_json_files}" ] && [ -f "${modified_json_files}" ]  ; then
    	rm "${modified_json_files}"
    fi
}

set -e

trap cleanup EXIT INT HUP

if [ -z "${UCT_IGNORE_CHECK_SYNTAX}" ] ; then
    modified_files="$(mktemp -t ucthook-XXXXXXXXXX)"
    modified_json_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}"
    git diff --cached --name-only --diff-filter=AM $against | grep ".json$" | sed "s|^|${dir}/|" > "${modified_json_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
	    exit 1
	fi
    fi

    if [ -s "${modified_json_files}" ]; then
	    if ! "${UCT}/scripts/check-json-syntax" "${modified_json_files}"; then
		    echo "Found syntax errors on some .json files"
		    exit 1
	    fi
    fi

    if grep ignored/not-for-us.txt "${modified_files}"; then
      if ! "${UCT}/scripts/validate-nfu.py"; then
        echo "Found syntax errors on ignored/not-for-us.txt"
        exit 1
      fi
    fi

    if [ -d $SUBPROJECTS ]; then
        subproject_untracked=$(git -C $SUBPROJECTS status --porcelain | awk '{print $2}')
        if [ ! -z "${subproject_untracked}" ]; then
            echo "Please commit changes in the subprojects directory:"
            for file in ${subproject_untracked}; do
	        echo $file
            done
        fi
    fi
fi
