#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2026 Romain Maneschi <romain@gitroot.dev>
#
# SPDX-License-Identifier: EUPL-1.2

_init() {
    local SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
    source "${SCRIPT_DIR}/report.sh"
    source "${SCRIPT_DIR}/git.sh"
}

_init
unset -f _init

# push_and_wait <remote> <branch>...
#   Push then sleep 0.1 sec then push again, display time waiting after all.
function push_and_wait() {
    start=`date +%s.%N`
    quiet_git push "$@"
    sleep 0.1
    local attempts=0
    while true; do
        ((attempts++))
        output=$(LANG=C git push "$@" 2>&1)
        if echo "$output" | grep -q "\[rejected\]"; then
            break
        fi
        if [ $attempts -gt 50 ]; then
            report "🛑 Timeout : too much try"
            break
        fi
        sleep 0.5
    done
    end=`date +%s.%N`
    runtime=$( echo "$end - $start" | bc -l )
    min=$(echo "$runtime / 60" | bc)
    sec=$(echo "$runtime % 60" | bc | xargs printf "%06.3f")
    report "🕐 waiting pipeline ${min}m ${sec}s"
}