#!/bin/bash
# Shared helper: git push with retry and rebase
# Handles race conditions when multiple CircleCI pipelines push to tbi-environments concurrently
#
# Usage: source this file, then call git_push_with_retry
#   source /path/to/git-push-with-retry.sh
#   git_push_with_retry <branch>

git_push_with_retry() {
    local branch="${1:-master}"
    local max_retries=5
    local attempt=1
    while [ $attempt -le $max_retries ]; do
        if git push origin "$branch" 2>&1; then
            return 0
        fi
        echo "⚠️  Push failed (attempt ${attempt}/${max_retries}), rebasing and retrying..."
        git pull --rebase origin "$branch"
        attempt=$((attempt + 1))
    done
    echo "ERROR: Failed to push after ${max_retries} attempts"
    return 1
}
