#!/bin/sh -e
#
# This hook adds a comment for guidance about the commit message
# format on top of the default commit message.
#
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source.	The hook's purpose is to edit the commit
# message file.	If the hook fails with a non-zero status,
# the commit is aborted.

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

beginswith() { case $2 in "$1"*) true;; *) false;; esac; }

original=$(cat "$COMMIT_MSG_FILE")
if beginswith $'\n#' "$original"; then
	# Find common path prefix of changed files
	path=$(while read file
		do test -z "$count" && common="$file" && count=$(expr length "$file") ||
			while expr substr "$file" 1 $count != substr "$common" 1 $count >/dev/null
			do let count--
			done
		done <<<"$(git -P diff --cached --name-only -r)" &&
			expr substr "$common" 1 "$count" | sed 's|.local/bin/scripts|bin|') || exit 0
	case "$path" in ([0-9]-*) path="${path#*-}";; esac
	{
		# Remove initial dot and trailing slash/dash/underscore
      echo "$path" | sed 's|^\.||;s|[/_-]\?$|: |'
		echo "$original"
	} > "$COMMIT_MSG_FILE"
fi