#! /bin/sh

# `try_repeat` tries to run a command *n* times, exiting early if the command
# exits with a non-zero exit code. This is useful when trying to find
# intermittent failures in a command.

usage() {
    echo "Usage: try_repeat [-hv] <count> <command> [<arg1> ... <argn>]" > /dev/stderr
    exit 1
}

verbose=0
while getopts ":hv" f
do
    case "$f" in
        h)   usage;;
        v)   verbose=1;;
        [?]) usage;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -lt 2 ]; then
    usage
fi

i=0
count=$1
shift
while [ $i -lt $count ]; do
    if [ $verbose -ne 0 ]; then
        echo "===> $((i + 1)): $@"
    fi
    "$@" || exit $?
    i=$(($i + 1))
done
