#!/bin/sh -eu

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

# env: GIRAR_USER_PREFIX GIRAR_USER GIT_DIR
GIRAR_USER_PREFIX=${GIRAR_USER_PREFIX:?}
GIRAR_USER=${GIRAR_USER:?}
GIT_DIR=${GIT_DIR:?}

# Globals
git_aliases="$GIRAR_EMAIL_ALIASES"
maildir="$GIRAR_EMAIL_DIR"

[ "$#" -ge 3 ] ||
	fatal "Wrong number of arguments: $#"

project_name="$1"; shift
ref_style="$1"; shift
ref_name="$1"; shift

git_dir="$(readlink -ev "$GIT_DIR")"
project_type="${git_dir%/*}"
project_type="${project_type##*/}"
project_type_quoted="$(quote_sed_regexp "$project_type")"

translate_email()
{
	local a
	while read a; do
		if [ -z "${a##*@*}" ]; then
			valid_email "$a" ||
				fatal "invalid email address: $a"
			printf '%s\n' "$a"
			continue
		fi
		a="$(quote_sed_regexp "$a")"
		sed -ne "s/^${GIRAR_USER_PREFIX}$a:[[:space:]]\\+\\([^[:space:]]\\+\\).*/\\1/p" "$git_aliases"
	done
}

expand_match()
{
	local mask= match= name sym prefix=

	# create a "???" mask
	name="$1"
	while [ -n "$name" ]; do
		mask="${mask}?"
		name="${name#?}"
	done

	name="$1"
	while [ -n "$name" ]; do
		mask="${mask#?}"
		sym="${name%$mask}"
		sym="$(quote_sed_regexp "$sym")"
		name="${name#?}"
		prefix="${prefix}${sym}"
		match="${match}${sym}\?"
	done

	match="\\($match\\*\\|$prefix\\)"
	printf %s "$match"
}

find_subscribers()
{
	local u p t n

	u="$(expand_match "$GIRAR_USER")"
	p="$(expand_match "$project_name")"
	t="$(expand_match "$ref_style")"
	n="$(expand_match "$ref_name")"

	grep -ls "^$u[[:space:]]\\+$p[[:space:]]\\+$t[[:space:]]\\+$n[[:space:]]*\$" "$maildir/$project_type"/*/subscription |
		sed -ne "s|^$maildir/$project_type_quoted/\\([^/]\\+\\)/subscription\$|\\1|p"

	[ ! -f "$maildir/$project_type/$GIRAR_USER/distribution" ] ||
		sed -ne "s/^$p[[:space:]]\\+$t[[:space:]]\\+$n[[:space:]]\\+//p" "$maildir/$project_type/$GIRAR_USER/distribution" |
		tr -s ',[:space:]' '\n'

	[ ! -r "$GIT_DIR/mailto" ] ||
		cat "$GIT_DIR/mailto"
}

find_subscribers |
	translate_email |
	sed -e '/^[[:space:]]*$/d' -e 's/^[[:space:]]\+//' -e 's/[[:space:]]\+$//' |
	sort -u
