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

# post-receive
# this accepts multiple lines of input at a time
# it defers exit on failure until after all scripts have run

my_input=$(cat)
my_dir=$(dirname $0)
my_success="true"

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

	# Let the user know if the hook isn't executable, but don't bail
	if [ ! -x "${my_hook}" ] || [ ! -f "${my_hook}" ]; then
		>&2 echo "${my_hook} is not (or does not point to) an executable file"
	fi

	# Allow the script to fail so we can bubble the exit code and ensure an error message
	set +e
	echo "${my_input}" | ("${my_hook}")
	my_exit_code=$?
	set -e

	# Don't bail on script failure
	if [ "0" != "${my_exit_code}" ]; then
		my_success=""
		>&2 echo "${my_hook} failed with exit code ${my_exit_code}"
	fi
done

if [ -z "${my_success}" ]; then
	echo "some post-receives failed"
	exit 156
fi
