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

REPOGOON_CONFIG="${REPOGOON_CONFIG:-/etc/repogoon/config.yml}"
CONFIG_INTERNAL_SECRET=""
if [ -f "$REPOGOON_CONFIG" ]; then
    if command -v yq >/dev/null 2>&1; then
        CONFIG_INTERNAL_SECRET=$(yq '.server.internalSecret // ""' "$REPOGOON_CONFIG" 2>/dev/null | sed 's/^"//' | sed 's/"$//')
    else
        CONFIG_INTERNAL_SECRET=$(grep -E '^[[:space:]]*internalSecret:' "$REPOGOON_CONFIG" 2>/dev/null | head -1 | awk -F: '{print $2}' | xargs)
    fi
fi
if [ -n "$CONFIG_INTERNAL_SECRET" ]; then
    REPOGOON_INTERNAL_SECRET="$CONFIG_INTERNAL_SECRET"
else
    REPOGOON_INTERNAL_SECRET="${REPOGOON_INTERNAL_SECRET:-}"
fi

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

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

    repo_path=$(cd "${GIT_DIR:-.}" && pwd)
    namespace=$(basename "$(dirname "$repo_path")")
    repo=$(basename "$repo_path" .git)
    internal_url=${REPOGOON_INTERNAL_URL:-http://127.0.0.1:3001}
    if [ -n "$REPOGOON_INTERNAL_SECRET" ]; then
        curl --silent --show-error --fail \
            -H "Content-Type: application/json" \
            -H "X-Internal-Secret: ${REPOGOON_INTERNAL_SECRET}" \
            --data "{\"namespace\":\"${namespace}\",\"repo\":\"${repo}\",\"ref\":\"${refname}\",\"newrev\":\"${newrev}\"}" \
            "${internal_url}/api/internal/pipeline-push" >/dev/null 2>&1 || true
    fi

    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
