#!/bin/sh -e
#
# To be executed by git (symbolically link as .git/hooks/pre-receive)
# For each commit, verify each hook configured for the repo
##

# TODO Generalize this for upstream names ending in .git
declare GIT_DIR="$(pwd)"
declare REPO="$(basename $GIT_DIR)"
# Since this is typically run via symbolic link, figure out where we're really
# ...running.
declare BART_HOOKS="$(dirname $(readlink $0))"


# This hook is provided with all commits on all branches that the user has pushed
# User can push multiple branches at the same time, and multiple commits for each branch
# The main 'while' loop goes over each branch.
# The inner 'for' loop goes ever each commit on that branch
while true; do
	read oldhead newhead branch || exit 0

	# Check if we're done looping thru every branch
	if [ -z "$oldhead" -a -z "$newhead" -a -z "$branch" ]; then
		exit 0
	fi

	# Check if we have everything as expected
	if [ -z "$oldhead" -o -z "$newhead" -o -z "$branch" ]; then
		echo >&2 "Unexpected: One of the required parameters is empty"
		echo >&2 "oldhead: $oldhead, newhead: $newhead, branch: $branch"

		exit 1
	fi

	# TODO generalize this for other branches
	branch=${branch##refs/heads/}
	if [ "$branch" != "dev" ]; then
		continue
	fi

	for commit_hash in $(git --git-dir=$GIT_DIR rev-list $oldhead..$newhead)
	do
		# This script does all the work and will exit 0 or 1 based on success
		php $BART_HOOKS/pre-receive.php \
			--git-dir $GIT_DIR \
			--repo $REPO \
			"$commit_hash"

		if [[ $? -ne 0 ]]; then
			echo >&2 "
			Hooks failed."
			exit 1
		fi
	done
done

