#!/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

usr_type_regexp="s@.*/$GIRAR_USER/\\([^/]*\\)/[^/]\+\\.git@\1@"
prj_type_regexp="s@.*/\\(projects\\)/.\+\\.git@\1@"
def_type_regexp='s@.*/\(.*\)/.*\.git@\1@'

git_dir="$(readlink -ev "$GIT_DIR")"
project_type=$(printf %s "$git_dir"| sed -e "$usr_type_regexp" -e "$prj_type_regexp" -e "$def_type_regexp")
quote_sed_regexp_variable project_type_quoted "$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
		quote_sed_regexp_variable a "$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}"
		quote_sed_regexp_variable sym "$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'

	[ ! -f "$GIRAR_SUBSCRIPTION_LIST" ] ||
		sed -ne "s/^$p[[:space:]]\\+$t[[:space:]]\\+$n[[:space:]]\\+//p" "$GIRAR_SUBSCRIPTION_LIST" |
		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
