#!/bin/bash

# Copyright (C) 2021 UBports Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Ratchanan Srirattanamet <ratchanan@ubports.com>

# This script repeat a command for a set amount of time until it succeeded.
# This is intended to be like ctest's `--repeat until-pass:<n>`, but that
# option is added in CMake 3.17 and Ubuntu 20.04 has 3.16. So, this is written
# as a replacement.

# The number of attempts (default is 3)
REPEAT_UNTIL_PASS_ATTEMPTS=${REPEAT_UNTIL_PASS_ATTEMPTS:-3}

echo "Will run \"$*\" for up to ${REPEAT_UNTIL_PASS_ATTEMPTS} times until it passes."

for ((i=1; i <= REPEAT_UNTIL_PASS_ATTEMPTS; i++)); do
    echo "Running $1, attempt ${i}/${REPEAT_UNTIL_PASS_ATTEMPTS}"
    "$@"; ret=$?

    if [ "$ret" = 0 ]; then
        echo "Attempt ${i}/${REPEAT_UNTIL_PASS_ATTEMPTS}, $1 finishes successfully."
        break
    else
        echo "Attempt ${i}/${REPEAT_UNTIL_PASS_ATTEMPTS}, $1 finishes with status ${ret}"
    fi
done

if [ "$ret" != 0 ]; then
    echo "Out of attempts; exits with the last status."
fi

exit "$ret"
