#!/bin/bash
#
# A hook to add [$branch] to the beginning of a commit message
# if certain conditions are met.
#
# This is a prepare-commit-msg hook.
#
# To install this you can either copy or symlink it to
# $GIT_DIR/hooks, example:
#
# ln -s ../../git-tools/hooks/prepare-commit-msg \\
#   .git/hooks/prepare-commit-msg

# get branch name
branch="$(git symbolic-ref HEAD)"

# exit if no branch name is present
# (eg. detached HEAD)
if [ $? -ne 0 ]
then
	exit
fi

# strip off refs/heads/
branch="$(echo "$branch" | sed "s/refs\/heads\///g")"

# add [branchname] to commit message
# * only run when normal commit is made (without -m or -F;
#   not a merge, etc.)
# * also make sure the branch name begins with bug/ or feature/
if [ "$2" = "" ]
then
	tail="";
	ticket_id=$(sed -E 's/(ticket\/)(security\/)?([0-9]+)(.+$)?/\3/gm;t;d' <<< "$branch");
	branch_title=$(sed -E 's/(ticket\/)(security\/)?([0-9]+)(.+$)?/\1\2\3/gm;t;d' <<< "$branch");

	if [ "security/" = "$(sed -E 's/(ticket\/)(security\/)?([0-9]+)(.+$)?/\2/gm;t;d' <<< "$branch")" ];
	then
		tail="$(printf '\n\nSECURITY-%s' "$ticket_id")";
	else
		# Branch is prefixed with 'ticket/', append ticket ID to message
		if [ "$branch" != "${branch##ticket/}" ];
		then
			tail="$(printf '\n\nPHPBB3-%s' "$ticket_id")";
		fi
	fi

	echo "[$branch_title] $tail$(cat "$1")" > "$1"
fi