#!/usr/bin/bash
# RepoGoon post-receive hook
# Records the authenticated RepoGoon username for commits received over Git transport.

if [ -z "$REMOTE_USER" ]; then
    exit 0
fi

export GIT_AUTHOR_NAME="${REPOGOON_GIT_TAGGER_NAME:-RepoGoon}"
export GIT_AUTHOR_EMAIL="${REPOGOON_GIT_TAGGER_EMAIL:-repogoon@localhost}"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"
export GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"

while read oldrev newrev refname; do
    if [ "$newrev" = "0000000000000000000000000000000000000000" ]; then
        continue
    fi

    case "$refname" in
        refs/heads/*) ;;
        *) continue ;;
    esac

    if [ "$oldrev" = "0000000000000000000000000000000000000000" ]; then
        other_refs=$(git for-each-ref --format='%(refname)' refs/heads refs/tags | grep -v "^${refname}$" || true)
        if [ -n "$other_refs" ]; then
            commits=$(git rev-list "$newrev" --not $other_refs 2>/dev/null)
        else
            commits=$(git rev-list "$newrev" 2>/dev/null)
        fi
    else
        commits=$(git rev-list "${oldrev}..${newrev}" 2>/dev/null)
    fi

    printf '%s\n' "$commits" | while read commit; do
        if [ -z "$commit" ]; then
            continue
        fi
        printf '%s\n' "$REMOTE_USER" | git notes --ref=repogoon-pusher add -f -F - "$commit" >/dev/null 2>&1 || true
    done
done

exit 0
