#!/usr/bin/env bash
set -u
set -e

# pre-receive
# this accepts multiple lines of input at a time
# it fails at the first of any child script failing

my_input=$(cat)
my_dir=$(dirname $0)

for my_hook in ${my_dir}/pre-receive.d/*; do

	# Bail and let the user know if the hook isn't executable
	if [ ! -x "${my_hook}" ] || [ ! -f "${my_hook}" ]; then
		>&2 echo "${my_hook} is not (or does not point to) an executable file"
		exit 155
	fi

	# Allow the script to fail so we can bubble the exit code and ensure an error message
	# and subscript it so that any set -e won't cause this to fail
	set +e

	# foo="$(echo bar; exit 3)"; echo $?; echo $foo
	#my_output="$(echo "${my_input}" | "${my_hook}")"
	echo "${my_input}" | ("${my_hook}")
	my_exit_code=$?
	set -e

	#echo my_output: $my_output

	# Bail on the first script failure
	if [ "0" != "${my_exit_code}" ]; then
		>&2 echo "${my_hook} failed with exit code ${my_exit_code}"
 		exit ${my_exit_code}
	fi
done