#!/bin/sh -efu

[ "$project_type" = etc ] || exit 0

. girar-sh-functions
. shell-mail-address

validate_distribution_subscription()
{
	local where="$1"; shift
	local p="$1"; shift
	local t="$1"; shift
	local n="$1"; shift
	local rest="$1"; shift

	[ -z "$rest" ] ||
		fatal "$where: unexpected field: $rest"

	[ "$p" = '*' ] ||
	printf %s "$p" |egrep -qs "$project_name_regexp" ||
	printf %s "${p%\*}" |egrep -qs "$project_name_regexp" ||
		fatal "$where: invalid package pattern: $p"
	case "$t" in
		\*|head|tag|remote) ;;
		*) fatal "$where: invalid reftype pattern: $t" ;;
	esac
	[ "$n" = '*' ] ||
	git check-ref-format "refs/$n" ||
		fatal "$where: invalid refname pattern: $n"
}

validate_email_list()
{
	local where="$1"; shift
	local addr="$1"; shift
	local a="$(printf %s "$addr" |tr , ' ')"
	set -- ${a}
	for a; do
		if [ -z "${a##*@*}" ]; then
			valid_email "$a" ||
				fatal "$where: invalid email address: $a"
			continue
		fi
		cut -f1 -- "${GIRAR_EMAIL_ALIASES}" |
			fgrep -xqs "${GIRAR_USER_PREFIX}$a:" ||
			fatal "$where: invalid email list: user $a not found."
	done
}

validate_email_distribution()
{
	local p t n a rest line=0
	while read -r p t n a rest; do
		line="$((1+$line))"
		[ -n "$a" ] ||
			fatal "email-distribution:$line: insufficient fields."
		validate_distribution_subscription \
			"email-distribution:$line" \
			"$p" "$t" "$n" "$rest"
		validate_email_list "email-distribution:$line" "$a"
	done
}

validate_email_subscription()
{
	local u p t n rest line=0
	while read -r u p t n rest; do
		line="$((1+$line))"
		[ -n "$n" ] ||
			fatal "email-subscription:$line: insufficient fields."
		validate_distribution_subscription \
			"email-subscription:$line" \
			"$p" "$t" "$n" "$rest"
		[ "$u" != '*' ] ||
			continue
		printf %s "$u" |egrep -qs "$user_name_regexp" ||
			fatal "$where: invalid user name: $u"
		[ -d "$GIRAR_HOME/$u" ] ||
			fatal "$where: unknown user name: $u"
	done
}

check_unsupported()
{
	local re="^($1)\$"; shift
	local out
	out="$(git diff-tree --name-only "$arg_oldrev" "$arg_newrev" -- |egrep -v "$re")" ||
		return 0
	fatal "unsupported files: $(printf %s "$out" |tr -s '[:space:]' ' ')"
}

check_update()
{
	local t="$1"; shift
	local n="$1"; shift
	git diff-tree --name-only "$arg_oldrev" "$arg_newrev" -- "$t-$n" |
		fgrep -qse "$t-$n" ||
			return 0
	git cat-file blob "$arg_newrev:$t-$n" 2>/dev/null |
		egrep '^[[:space:]]*[^#[:space:]]' |
		"validate_${t}_$n"
}

check()
{
	local i list=
	for i; do
		check_update "${i%%-*}" "${i#*-}"
		list="$list|$i"
	done
	list="${list#|}"
	check_unsupported "$list"
}


[ "$arg_refname" = 'refs/heads/master' ] ||
	fatal "Unsupported ref name: $arg_refname"

case "$project_name" in
	packages)
		check email-distribution email-subscription
		;;
	projects)
		check email-distribution email-subscription
		;;
	private)
		check email-distribution
		;;
	public)
		check email-distribution email-subscription
		;;
	*)
		fatal "Unsupported repository: $project"
		;;
esac
