#!/bin/sh -e
# shellcheck disable=SC2048,SC2086

RETRY="${RETRY:-3}"
STABILITY_TEST="${STABILITY_TEST:-0}"
# Pass a hook command which is executed if a retry occurs
HOOK="${HOOK:-}"

run_once() {
    $*
}

if [ "$RETRY" = "0" ]; then
    run_once $*
else
    n=1
    while :; do
        if [ "$STABILITY_TEST" = "0" ]; then
            [ $n -le "$RETRY" ] || exit 1
            [ $n -eq 0 ] || echo "Retry $n of $RETRY …"
            run_once $* && break
        else
            [ $n -le "$RETRY" ] || exit 0
            run_once $* || exit
            echo "Rerun $n of $RETRY …"
        fi
        if [ -n "$HOOK" ]; then
            echo "Calling retry hook $HOOK"
            RETRY_ATTEMPT=$n "$HOOK"
        fi
        n=$((n+1))
    done
fi
