#!/usr/bin/env bash
#
# Source this file in a pre- or post-receive hook
# For each commit, verify each hook configured for the repo
##

# Verify required parameter(s) provided by including script
if [[ -z "$HOOK_SCRIPT" ]]; then
	echo >&2 'Must define $HOOK_SCRIPT'
	exit 1
fi

if [[ -z "$GIT_DIR" || -z "$REPO" || -z "$BART_HOOKS" ]]; then
	echo >&2 'Missing required metadata variables'
	exit 1
fi

# House keeping
# TODO Ideally, should be its own post-receive hook class
git --git-dir="$GIT_DIR" update-server-info -f
git --git-dir="$GIT_DIR" gc --auto

# 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" && "$branch" != "master" ]]; 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/$HOOK_SCRIPT \
			--git-dir $GIT_DIR \
			--repo $REPO \
			"$commit_hash"

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


