#!/bin/sh
set -eu

zero="0000000000000000000000000000000000000000"
needs_check=0

while read -r local_ref local_sha remote_ref remote_sha; do
	[ "$local_sha" = "$zero" ] && continue
	needs_check=1

	case "$local_ref" in
		refs/heads/main) ;;
		refs/heads/feature/*|refs/heads/fix/*|refs/heads/integration/*|refs/heads/docs/*|refs/heads/chore/*|refs/heads/release/*) ;;
		refs/tags/*) ;;
		*)
			printf '%s\n' "Nom de branche refuse : ${local_ref#refs/heads/}" >&2
			printf '%s\n' "Utilisez feature/, fix/, integration/, docs/, chore/ ou release/." >&2
			exit 1
			;;
	esac

	if [ "$remote_sha" != "$zero" ] && ! git merge-base --is-ancestor "$remote_sha" "$local_sha"; then
		printf '%s\n' "Push non fast-forward refuse pour ${remote_ref#refs/heads/}." >&2
		exit 1
	fi
done

if [ "$needs_check" -eq 1 ]; then
	git diff --check
	./gradlew --no-daemon check
fi
